package com.outsourcing.bottle.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.view.ext.SatelliteMenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.aviary.android.feather.library.media.ExifInterfaceWrapper;
import com.aviary.android.feather.library.moa.MoaHD;
import com.aviary.android.feather.library.moa.MoaHD.Error;
import com.aviary.android.feather.library.providers.FeatherContentProvider;
import com.aviary.android.feather.library.providers.FeatherContentProvider.ActionsDbColumns.Action;
import com.aviary.android.feather.library.utils.DecodeUtils;
import com.aviary.android.feather.library.utils.IOUtils;
import com.aviary.android.feather.library.utils.ImageLoader.ImageSizes;
import com.aviary.android.feather.library.utils.StringUtils;
import com.aviary.android.feather.library.utils.SystemUtils;
import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.BottleTypeTable;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.db.PushNoticeInfoTable;
import com.outsourcing.bottle.domain.BottleFeedListEntry;
import com.outsourcing.bottle.domain.BottleFeedListInfo;
import com.outsourcing.bottle.domain.BottleFeedLocationEntry;
import com.outsourcing.bottle.domain.BottleFeedLocationInfo;
import com.outsourcing.bottle.domain.BottleInfo;
import com.outsourcing.bottle.domain.BottleInfoEntry;
import com.outsourcing.bottle.domain.BottleLikeEntry;
import com.outsourcing.bottle.domain.BottleLikeListInfo;
import com.outsourcing.bottle.domain.BottleTypeEntry;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.PushNoticeInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ImageLoader;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.util.Utility;
import com.outsourcing.bottle.widget.CustomGridView;
import com.outsourcing.bottle.widget.CustomPopupWindow;
import com.outsourcing.bottle.widget.ElasticScrollView;
import com.outsourcing.bottle.widget.TryRefreshableView;

@TargetApi(8)
public class BottleDetailActivity extends BasicActivity implements
		BasicUIEvent, OnClickListener, Callback {
	private static final String TAG = BottleDetailActivity.class.getSimpleName();

	private static final int EXEU_GET_BOTTLE_INFO = 0;
	private static final int EXEU_GET_BOTTLE_INFO_FAILED = 1;
	private static final int EXEU_BOTTLE_FEEDLIST = 2;
	private static final int EXEU_BOTTLE_LIKELIST = 3;

	private static final int EXEU_GET_DATA_ERROR = 4;
	private static final int EXEU_REFRESH_CONTENT = 5;
	private static final int EXEU_BOTTLE_LOAD_MAP = 6;
	private static final int EXEU_GET_LOCATION_LIST = 7;

	private static final int EXEU_GET_BOTTLE_PRIV_OPERATION = 8;
	private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS = 9;
	private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE = 10;
	private static final int EXEU_SEND_BOTTLE_PRIV_FAILED = 11;

	private static final int EXEU_LIKE_OPERATION = 12;
	private static final int EXEU_UNLIKE_OPERATION = 13;
	private static final int EXEU_LIKE_OPERATION_FAILED = 14;
	private static final int EXEU_REFRESH_BOTTLE_LIST = 15;
	private static final int EXEU_GET_MORE_CONTENT = 16;

	private static final int EXEU_GET_DATA_NOTHING = 17;
	
	private final int throw_bottle_init_location = 18;

	private static final int EXEU_DELETE_LOCATION = 19;
	
	View mContentView = null;
	ElasticScrollView elasticScrollView = null;
	private RelativeLayout rl_bt_detail_content;
	private LinearLayout ll_botle_scrfeed = null;
	private ImageView iv_back;
	private ImageView iv_menu;
	private ImageView iv_avater;
	private ImageView iv_bottle_type;
	private TextView tv_nickname;
	private TextView tv_tag;
	private TextView tv_location;
	private TextView tv_distance;
	private TextView tv_copy;
	private TextView tv_mood;
	
	private Button bt_drawing;
	private Button bt_allow_draw;
	
	private Button bt_comment;
	private Button bt_copy;
	private Button bt_forward;
	private LinearLayout rl_like;
	private ImageView iv_like_icon;
	private ImageView iv_map;
	private ImageView iv_like;
	private TextView tv_message;
	private ImageView iv_photo;
	// ListView listView;
	private CustomGridView like_grid;
	private LinearLayout mFeedCommentContent;
	private RelativeLayout rl_button_like = null;
	CustomPopupWindow mLikePopview;
	private Handler handler = null;
	private List<BottleLikeEntry> mLikeEntries = null;
	private List<BottleFeedListEntry> mListEntries = null;
	private List<BottleFeedLocationEntry> mLocationEntries = null;
	private GridLikeAdapter gridAdapter = null;
	private int btId;
	private int btTypeId;
	private BottleTypeEntry entry;
	/**
	 * 1.LikeList 2.Location
	 */
	private int type;
	private int page = 1;

	private float bottle_lat, bottle_lon;
	private Bitmap bitmap = null;
	private BottleInfoEntry bottleInfoEntry = null;

	private ImageLoader imageLoader = null;
	private ImageLoader btConfigLoader;

	private RelativeLayout rl_bottle_content_photo;
	private LinearLayout ll_botle_op_location;
	private LinearLayout ll_bottle_photo_locked;
	private TextView like_num;
//	private ImageView messageView;
	private TryRefreshableView rv;
	private LinearLayout ll_content;
	private ScrollView sv;

	private LinearLayout ll_bottle_location;

	private String location = "";

	private int likeType;
	private final int menu_uploadphoto = 105;
	private final int menu_exprofile = 104;
	private final int menu_exphoto = 103;
	private final int menu_gainbt = 102;
	private final int menu_sendbt = 101;
	private final int user_baseinfo_notfull = 100;

	private LinearLayout bottomLayout;
	private RemoteImageView avatarView;
	private TextView contentView;
	private TextView btnCount;
	private int newNoticeCount;
	private int newMessageCount;
	private int newBottleFeedCount;
	private int newExchangeFeedCount;
	private int newMaybeKownCount;
	private String message_content;
	private String message_avatar;
	private PushBroadcastReceiver receiver;
	private PushNoticeInfo pushInfo;
	
	String mOutputFilePath;
	/** session id for the hi-res post processing */
	private String mSessionId;

	private static final int ACTION_REQUEST_FEATHER = 100;
	private static final int EXEU_SET_BTPIC_PAINT_SUCCESS = 101;

	private static final int EXEU_DELETE_LOCATION_SUCCESS = 102;

	private static final int EXEU_DELETE_LOCATION_FAILED = 103;

	private static final int EXEU_REFRESH_FEED_LIST = 104;

	private static final int EXEU_REFRESH_LOCATION_LIST = 105;
	
	private Uri fileUri;
	int imageWidth, imageHeight;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bottle_detail);

		DisplayMetrics metrics = getResources().getDisplayMetrics();
		imageWidth = (int) ( (float) metrics.widthPixels / 1.5 );
		imageHeight = (int) ( (float) metrics.heightPixels / 1.5 );
		
		btId = getIntent().getIntExtra("btid", 0);
		type = getIntent().getIntExtra("type", 0);
		handler = new Handler(this);
		imageLoader = new ImageLoader(this, AppContext.BottleTimelineIcon);
		btConfigLoader = new ImageLoader(this, AppContext.BOTTLE_CONFIG);
		initLayout();
		initLikePopup();
		initSateMenu();

		receiver = new PushBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("push");
		registerReceiver(receiver, filter);
		UICore.eventTask(this, BottleDetailActivity.this, EXEU_GET_BOTTLE_INFO, "", null);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (AppContext.getInstance().isBottleDetailActNeedRefresh()) {
			AppContext.getInstance().setBottleDetailActNeedRefresh(false);
			page = 1;
			UICore.eventTask(this, BottleDetailActivity.this,
					EXEU_GET_BOTTLE_INFO, "", null);
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case EXEU_BOTTLE_FEEDLIST:
			// getBottleFeedList(btId, page);
			break;
		case EXEU_BOTTLE_LIKELIST:
			getBottleLikesList(btId, page);
			break;
		case EXEU_GET_BOTTLE_INFO:
			getBottleInfo(btId);
			switch (type) {
			case 1:
				getBottleLikesList(btId, page);
				getBottleFeedList(btId, page);
				break;
			case 2:
				getFeedLocationList(page);
				break;
			default:
				break;
			}

			break;
		case EXEU_REFRESH_CONTENT:
			getBottleInfo(btId);
			switch (type) {
			case 1:
				getBottleLikesList(btId, page);
				getBottleFeedList(btId, page);
				break;
			case 2:
				getFeedLocationList(page);
				break;
			default:
				break;
			}
			break;
		case EXEU_BOTTLE_LOAD_MAP:
			String language = AppContext.language == 1?"zh":"en";
			String url_map = UrlConfig.map_static_url
					+ "?center="
					+ bottle_lat
					+ ","
					+ bottle_lon
					+ "&zoom=15&language="+language+"&size="
					+ CanvasWidth
					+ "x"
					+ (CanvasHeight > 790 ? 120 : (CanvasHeight / 5))
					+ "&sensor=false&mobile=true&markers=color:red%7Clabel:C%7C"
					+ bottle_lat + "," + bottle_lon;
			ServiceUtils.dout(url_map);
			bitmap = HttpUtils.getBitmapFromUrl(this, url_map);
			if (null != bitmap) {
				Message message = Message.obtain(handler);
				message.what = EXEU_BOTTLE_LOAD_MAP;
				handler.sendMessage(message);
			}
			break;
		case EXEU_GET_BOTTLE_PRIV_OPERATION:
			getSendSingleBtPriv(btTypeId, btId);
			break;
		case EXEU_LIKE_OPERATION:
			likeOperation(btId, likeType);
			break;
		case EXEU_UNLIKE_OPERATION:
			likeOperation(btId, likeType);
			break;
		case EXEU_REFRESH_BOTTLE_LIST:
			refreshBottleLikesList(btId);
			break;
		case EXEU_SET_BTPIC_PAINT_SUCCESS:
			int optype = (Integer)obj;
			setBtpicPaint(btId, optype);
			break;
		case EXEU_GET_MORE_CONTENT:
			getMoreBottleFeedList(btId, page);
			break;
		case throw_bottle_init_location:
			Object idObj = obj;
			networkLocat();
			Message msg = Message.obtain(handler, throw_bottle_init_location, idObj);
			handler.sendMessage(msg);
			break;
		case EXEU_DELETE_LOCATION:
			BottleFeedListEntry message = (BottleFeedListEntry)obj;
			deleteLocation(String.valueOf(message.getLocation_objtype()), String.valueOf(message.getLocation_objid()));
			break;
		case EXEU_REFRESH_FEED_LIST:
			refreshBottleFeedList(btId, 1);
			break;
		case EXEU_REFRESH_LOCATION_LIST:
			refreshBottleLocationList(btId,1);
			break;
		default:
			break;
		}
	}

	private void refreshBottleLocationList(int btId2, int i) {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_feedslocation);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&count=10");
		url.append("&page=" + page);
		ServiceUtils.dout("refreshBottleLocationList url: " + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("refreshBottleLocationList results:"
					+ results.toString());
			Gson gson = new Gson();
			BottleFeedLocationInfo bottleFeedLocationInfo = gson.fromJson(
					results, BottleFeedLocationInfo.class);
			if (bottleFeedLocationInfo.getResults().getAuthok() == 1) {
				mLocationEntries = bottleFeedLocationInfo
						.getBtfeedslocation_list();
				Message message = handler.obtainMessage(EXEU_REFRESH_LOCATION_LIST,
						bottleInfoEntry);
				handler.sendMessage(message);
			} else {
				Message message = Message.obtain(handler);
				message.what = EXEU_GET_BOTTLE_INFO_FAILED;
				handler.sendMessage(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
			Message message = Message.obtain(handler);
			message.what = EXEU_GET_BOTTLE_INFO_FAILED;
			handler.sendMessage(message);
		}
	}

	private void refreshBottleFeedList(int btId2, int page) {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_feedslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&count=14");
		url.append("&page=" + page);
		ServiceUtils.dout("refreshBottleFeedList url: " + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());

			if (result == null) {
				return;
			}
			ServiceUtils.dout("refreshBottleFeedList results:" + result.toString());
			Gson gson = new Gson();
			BottleFeedListInfo bottleFeedListInfo = gson.fromJson(result,
					BottleFeedListInfo.class);
			if (bottleFeedListInfo.getResults().getAuthok() == 1) {
				mListEntries = bottleFeedListInfo.getBtfeeds_list();
				if (null != mListEntries && mListEntries.size() > 0) {
					Message message = Message.obtain(handler);
					message.what = EXEU_REFRESH_FEED_LIST;
					handler.sendMessage(message);
				} else {
				}
			} else {
				Message message = handler.obtainMessage(EXEU_GET_DATA_ERROR,
						bottleFeedListInfo.getResults().getErrmsg());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
			Message message = Message.obtain(handler);
			message.what = EXEU_GET_BOTTLE_INFO_FAILED;
			handler.sendMessage(message);
		}
	}

	/** 获取扔瓶子的权限 */
	public void getSendSingleBtPriv(int btTypeId, int btId) {
		StringBuffer url = new StringBuffer(UrlConfig.get_sendsinglebt_priv);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&bttypeid=" + btTypeId);
		ServiceUtils.dout("sendsingleBT private url:" + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("getsendsinglebt_priv result:" + results);
			if (null != results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int authok = resultObj.getInt("authok");
				String errmsg = resultObj.getString("errmsg");

				if (authok == 1) {
					JSONObject privObj = obj.getJSONObject("sendsinglebt_priv");
					int enable = privObj.getInt("enable");
					String reason = privObj.getString("reason");

					if (enable == 1) {
						Bundle bundle = new Bundle();
						bundle.putInt("type", btTypeId);
						bundle.putInt("btid", btId);
						bundle.putString("reason", reason);
						Message message = handler
								.obtainMessage(EXEU_SEND_BOTTLE_PRIV_SUCCESS);
						message.setData(bundle);
						handler.sendMessage(message);
					} else {
						Message message = handler.obtainMessage(
								EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE,
								reason);
						handler.sendMessage(message);
					}

				} else {
					Message message = handler.obtainMessage(
							EXEU_SEND_BOTTLE_PRIV_FAILED, errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void initLayout() {
		iv_back = (ImageView) findViewById(R.id.topbar_back);
		iv_back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		iv_menu = (ImageView) findViewById(R.id.topbar_menu);
		iv_menu.setVisibility(View.INVISIBLE);
		if (type == 1) {
			iv_menu.setImageResource(R.drawable.menu_location);
		} else if (type == 2) {
			iv_menu.setImageResource(R.drawable.menu_feed);
		}
		iv_menu.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (type == 1) {
					Intent bottleDetailIntent = new Intent(
							BottleDetailActivity.this,
							BottleDetailActivity.class);
					bottleDetailIntent.putExtra("btid", btId);
					bottleDetailIntent.putExtra("type", 2);// 2,location
					startActivity(bottleDetailIntent);
				} else if (type == 2) {
					Intent bottleDetailIntent = new Intent(
							BottleDetailActivity.this,
							BottleDetailActivity.class);
					bottleDetailIntent.putExtra("btid", btId);
					bottleDetailIntent.putExtra("type", 1);// 2,location
					startActivity(bottleDetailIntent);
				}
			}
		});

//		messageView = (ImageView) findViewById(R.id.notice_message_count);
//		messageView.setOnClickListener(this);
		bottomLayout = (LinearLayout) findViewById(R.id.notice_bottom_layout);
		bottomLayout.setOnClickListener(this);
		avatarView = (RemoteImageView) findViewById(R.id.notice_avatar);
		contentView = (TextView) findViewById(R.id.notice_text);
		btnCount = (TextView) findViewById(R.id.notice_number);
		
		mContentView = LayoutInflater.from(this).inflate(
				R.layout.bottle_detail_content, null);
		rl_bt_detail_content = (RelativeLayout) mContentView
				.findViewById(R.id.rl_bt_detail_content);
		rl_bt_detail_content.setVisibility(View.INVISIBLE);
		iv_avater = (ImageView) mContentView.findViewById(R.id.iv_author_photo);

		iv_bottle_type = (ImageView) mContentView
				.findViewById(R.id.iv_bottle_type);

		tv_nickname = (TextView) mContentView.findViewById(R.id.tv_nickname);
		tv_tag = (TextView) mContentView.findViewById(R.id.tv_tag);
		tv_copy = (TextView) mContentView.findViewById(R.id.tv_copy_info);
		tv_message = (TextView) mContentView.findViewById(R.id.tv_doing);
		tv_mood = (TextView) mContentView.findViewById(R.id.tv_mood);
		ll_bottle_location = (LinearLayout) mContentView
				.findViewById(R.id.ll_bottle_location);
		tv_location = (TextView) mContentView.findViewById(R.id.tv_location);
		tv_distance = (TextView) mContentView.findViewById(R.id.tv_distance);
		
		ll_botle_op_location = (LinearLayout)mContentView.findViewById(R.id.ll_botle_op_location);
		ll_botle_scrfeed = (LinearLayout)mContentView.findViewById(R.id.ll_botle_scrfeed);
		
		rl_bottle_content_photo = (RelativeLayout) mContentView
				.findViewById(R.id.rl_bottle_content_photo);
		ll_bottle_photo_locked = (LinearLayout) mContentView
				.findViewById(R.id.ll_bottle_photo_locked);
		iv_photo = (ImageView) mContentView.findViewById(R.id.photo);
		
		bt_drawing = (Button)mContentView.findViewById(R.id.bt_drawing);
		bt_allow_draw = (Button)mContentView.findViewById(R.id.bt_allow_draw);
		
		bt_comment = (Button) mContentView.findViewById(R.id.bt_bottle_comment);
		bt_comment.setOnClickListener(this);
		bt_copy = (Button) mContentView.findViewById(R.id.bt_bottle_copy);
		bt_forward = (Button) mContentView.findViewById(R.id.bt_bottle_forward);
		rl_like = (LinearLayout) mContentView
				.findViewById(R.id.comment_button_like);
		rl_button_like = (RelativeLayout) mContentView
				.findViewById(R.id.rl_button_like);
		iv_like_icon = (ImageView) mContentView
				.findViewById(R.id.comment_button_like_icon);
		like_num = (TextView) mContentView
				.findViewById(R.id.comment_button_like_text);
		iv_map = (ImageView) mContentView.findViewById(R.id.iv_map);

		// iv_map.setOnClickListener(this);
		switch (type) {
		case 1:
			rl_like.setVisibility(View.VISIBLE);
			iv_map.setVisibility(View.GONE);
			break;
		case 2:
			rl_like.setVisibility(View.GONE);
			iv_map.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
		iv_like = (ImageView) mContentView
				.findViewById(R.id.comment_button_like_icon);
		iv_like.setBackgroundResource(R.drawable.like_red2);
		// listView = (ListView) mContentView.findViewById(R.id.list_view);

		like_grid = (CustomGridView) mContentView.findViewById(R.id.like_grid);
		// elasticScrollView.addChild(mContentView);

		like_grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				BottleLikeEntry btLike = (BottleLikeEntry) gridAdapter.getItem(position);
				Intent spaceIntent = new Intent(BottleDetailActivity.this, UserSpaceActivity.class);
				spaceIntent.putExtra("ouid", btLike.getLike_uid());
				startActivity(spaceIntent);
			}
		});

		mFeedCommentContent = (LinearLayout) mContentView
				.findViewById(R.id.ll_feed_comment_content);

		sv = (ScrollView) findViewById(R.id.trymySv);
		rv = (TryRefreshableView) findViewById(R.id.trymyRV);
		rv.mfooterView = (View) findViewById(R.id.tryrefresh_footer);
		rv.sv = sv;
		ll_content = (LinearLayout) findViewById(R.id.ll_content);
		// 隐藏mfooterView
		rv.mfooterViewText = (TextView) findViewById(R.id.tryrefresh_footer_text);
		rv.mfooterViewText.setVisibility(View.INVISIBLE);

		// 监听是否加载刷新
		rv.setRefreshListener(new TryRefreshableView.RefreshListener() {

			@Override
			public void onRefresh() {
				if (rv.mRefreshState == 4) {
					page = 1;
					UICore.eventTask(BottleDetailActivity.this,
							BottleDetailActivity.this, EXEU_REFRESH_CONTENT,
							null, null);
				} else if (rv.mfooterRefreshState == 4) {
					rv.mfooterViewText.setVisibility(View.VISIBLE);
					page++;
					UICore.eventTask(BottleDetailActivity.this,
							BottleDetailActivity.this, EXEU_GET_MORE_CONTENT,
							null, null);
				}

			}
		});

		ll_content.addView(mContentView);

	}

	private void initLikePopup() {
		LayoutInflater mLayoutInflater = LayoutInflater.from(this);
		View mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like_left,
				null);
		ImageView iv_unlike = (ImageView) mLikeView
				.findViewById(R.id.iv_unlike);
		ImageView iv_like = (ImageView) mLikeView.findViewById(R.id.iv_like);
		iv_unlike.setOnClickListener(this);
		iv_like.setOnClickListener(this);
		mLikePopview = new CustomPopupWindow(mLikeView,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLikePopview.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.like_frame_left));
		mLikePopview.setOutsideTouchable(true);
		mLikePopview.update();
		mLikePopview.setTouchable(true);
		mLikePopview.setFocusable(true);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_unlike:// 不喜欢
			mLikePopview.dismiss();
			likeType = 2;
			UICore.eventTask(this, this, EXEU_UNLIKE_OPERATION, "", null);
			break;
		case R.id.iv_like:// 喜欢
			mLikePopview.dismiss();
			likeType = 1;
			UICore.eventTask(this, this, EXEU_LIKE_OPERATION, "", null);
			break;
		case R.id.topbar_back:
			finish();
			break;
		case R.id.rl_button_like:
			showInfoPopupWindow(v);
			break;
		case R.id.bt_bottle_comment:
			Intent commentIntent = new Intent(this, ExpandEditActivity.class);
			Bundle commentBundle = new Bundle();
			commentBundle.putString("from_type", AppContext.REPLY_BT);
			commentBundle.putInt("bttype_id", btId);
			commentIntent.putExtras(commentBundle);
			startActivityForResult(commentIntent, 0);
			break;
		case R.id.bt_bottle_copy:
			Intent copyIntent = new Intent(this, ExpandEditActivity.class);
			Bundle copyBundle = new Bundle();
			copyBundle.putString("from_type", AppContext.COPYMANUAL_BT);
			copyBundle.putInt("bttype_id", btId);
			copyIntent.putExtras(copyBundle);
			startActivityForResult(copyIntent, 0);
			break;
		case R.id.bt_bottle_forward:

			final Context dialogContext = new ContextThemeWrapper(BottleDetailActivity.this,
					android.R.style.Theme_Light);
			String[] choices = new String[2];
			choices[0] = BottleDetailActivity.this.getString(R.string.bottle_txt_forward_to_friend);
			choices[1] = BottleDetailActivity.this.getString(R.string.bottle_txt_forward_to_platform);
			final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
					android.R.layout.simple_list_item_1, choices);

			final AlertDialog.Builder builder = new AlertDialog.Builder(
					dialogContext);
			builder.setTitle(R.string.system_info);
			builder.setSingleChoiceItems(adapter, -1,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							if (which == 0) {
								
								Intent forwardIntent = new Intent(BottleDetailActivity.this, ChooseFriendActivity.class);
								Bundle forwardBundle = new Bundle();
								forwardBundle.putInt("choose_friend_type", AppContext.CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE);
								forwardBundle.putInt("bttype_id", btId);
								forwardBundle.putString("return_type", BottleDetailActivity.class.getSimpleName());
								forwardIntent.putExtras(forwardBundle);
								startActivity(forwardIntent);	
							} else {
							
								Intent forwardIntent = new Intent(BottleDetailActivity.this, ExpandEditActivity.class);
								Bundle forwardBundle = new Bundle();
								forwardBundle.putString("from_type", AppContext.TRANSMIT_BT);
								forwardBundle.putInt("bttype_id", btId);
								forwardIntent.putExtras(forwardBundle);
								startActivityForResult(forwardIntent, 0);
							
							}
						}
					});
			builder.create().show();
			
			
			
			break;
		// case R.id.iv_map:
		// Intent intent = new Intent(this,MapViewActivity.class);
		// intent.putExtra("longitude", latidute);
		// intent.putExtra("latidute", longitude);
		// intent.putExtra("location", bottleInfoEntry.getBt_location());
		// break;
//		case R.id.notice_message_count:
//			doMessageAction();
//			break;
		default:
			break;
		}
	}


	/**
	 * Once you've chosen an image you can start the feather activity
	 * 
	 * @param uri
	 */
	private void startFeather( Uri uri ) {

		Log.d( TAG, "uri: " + uri );

		// first check the external storage availability
		if ( !Utility.isExternalStorageAvilable() ) {
//			showDialog( EXTERNAL_STORAGE_UNAVAILABLE );
			return;
		}

		// create a temporary file where to store the resulting image
		File file = Utility.getNextFileName();
		if ( null != file ) {
			mOutputFilePath = file.getAbsolutePath();
		} else {
			new AlertDialog.Builder( this ).setTitle( android.R.string.dialog_alert_title ).setMessage( "Failed to create a new File" )
					.show();
			return;
		}

		// Create the intent needed to start feather
		Intent newIntent = new Intent( this, CropImage2Activity.class );

		newIntent.putExtra( "From_Type", Constants.ACTIVITY_DRAW );
		
		// set the source image uri
		newIntent.setData( uri );

		// pass the required api_key and secret ( see
		// http://developers.aviary.com/ )
		newIntent.putExtra( "API_KEY", Utility.API_KEY );

		// pass the uri of the destination image file (optional)
		// This will be the same uri you will receive in the onActivityResult
		newIntent.putExtra( "output", Uri.parse( "file://" + mOutputFilePath ) );

		// format of the destination image (optional)
		newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name() );

		// output format quality (optional)
		newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 );

		// If you want to disable the external effects
		// newIntent.putExtra( Constants.EXTRA_EFFECTS_ENABLE_EXTERNAL_PACKS, false );

		// If you want to disable the external effects
		// newIntent.putExtra( Constants.EXTRA_STICKERS_ENABLE_EXTERNAL_PACKS, false );
		
		// enable fast rendering preview
		// newIntent.putExtra( Constants.EXTRA_EFFECTS_ENABLE_FAST_PREVIEW, true );

		// you can force feather to display only a certain ( see FilterLoaderFactory#Filters )
		// you can omit this if you just wanto to display the default tools

		/*
		 * newIntent.putExtra( "tools-list", new String[] { FilterLoaderFactory.Filters.ENHANCE.name(),
		 * FilterLoaderFactory.Filters.EFFECTS.name(), FilterLoaderFactory.Filters.STICKERS.name(),
		 * FilterLoaderFactory.Filters.ADJUST.name(), FilterLoaderFactory.Filters.CROP.name(),
		 * FilterLoaderFactory.Filters.BRIGHTNESS.name(), FilterLoaderFactory.Filters.CONTRAST.name(),
		 * FilterLoaderFactory.Filters.SATURATION.name(), FilterLoaderFactory.Filters.SHARPNESS.name(),
		 * FilterLoaderFactory.Filters.DRAWING.name(), FilterLoaderFactory.Filters.TEXT.name(),
		 * FilterLoaderFactory.Filters.MEME.name(), FilterLoaderFactory.Filters.RED_EYE.name(),
		 * FilterLoaderFactory.Filters.WHITEN.name(), FilterLoaderFactory.Filters.BLEMISH.name(),
		 * FilterLoaderFactory.Filters.COLORTEMP.name(), } );
		 */

		// you want the result bitmap inline. (optional)
		// newIntent.putExtra( Constants.EXTRA_RETURN_DATA, true );

		// you want to hide the exit alert dialog shown when back is pressed
		// without saving image first
		// newIntent.putExtra( Constants.EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION, true );

		// -- VIBRATION --
		// Some aviary tools use the device vibration in order to give a better experience
		// to the final user. But if you want to disable this feature, just pass
		// any value with the key "tools-vibration-disabled" in the calling intent.
		// This option has been added to version 2.1.5 of the Aviary SDK
		newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true );

		final DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics( metrics );
		int max_size = Math.min( metrics.widthPixels, metrics.heightPixels );

		// you can pass the maximum allowed image size, otherwise feather will determine
		// the max size based on the device memory
		// Here we're passing the current display size as max image size because after
		// the execution of Aviary we're saving the HI-RES image so we don't need a big
		// image for the preview
		max_size = (int) ( (double) max_size / 0.8 );
		Log.d( TAG, "max-image-size: " + max_size );
		newIntent.putExtra( "max-image-size", max_size );

		// Enable/disable the default borders for the effects
		newIntent.putExtra( "effect-enable-borders", true );

		// You need to generate a new session id key to pass to Aviary feather
		// this is the key used to operate with the hi-res image ( and must be unique for every new instance of Feather )
		// The session-id key must be 64 char length

		mSessionId = StringUtils.getSha256( System.currentTimeMillis() + Utility.API_KEY );
		Log.d( TAG, "session: " + mSessionId + ", size: " + mSessionId.length() );
		newIntent.putExtra( "output-hires-session-id", mSessionId );

		// ..and start feather
		startActivityForResult( newIntent, ACTION_REQUEST_FEATHER );
	}
	

	
	private void showInfoPopupWindow(View achorView) {

		if (mLikePopview.isShowing()) {
			mLikePopview.dismiss();
		} else {
			// mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0);
			mLikePopview.showAsDropDown(achorView, 60, -60);
		}
	}

	/**
	 * 喜欢瓶子的操作
	 * 
	 * @param btId
	 *            瓶子ID
	 * @param likeType
	 *            喜欢or不喜欢 <---> 1 or 2
	 */
	private void likeOperation(int btId, int likeType) {
		StringBuffer url = new StringBuffer(UrlConfig.likeop_bt);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&liketype=" + likeType);
		ServiceUtils.dout("likeOperation url:" + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("likeOperation result:" + results);
			if (null != results) {
				JSONObject obj = new JSONObject(results);
				JSONObject resultObj = obj.getJSONObject("results");
				int success = resultObj.getInt("success");
				String errmsg = resultObj.getString("errmsg");
				String successmsg = resultObj.getString("successmsg");
				Message message = null;
				if (success == 1) {

					switch (likeType) {
					case 1:
						message = handler.obtainMessage(EXEU_LIKE_OPERATION,
								successmsg);
						handler.sendMessage(message);
						break;
					case 2:
						message = handler.obtainMessage(EXEU_UNLIKE_OPERATION,
								successmsg);
						handler.sendMessage(message);
						break;
					default:
						break;
					}
				} else {
					message = handler.obtainMessage(EXEU_LIKE_OPERATION_FAILED,
							errmsg);
					handler.sendMessage(message);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getBottleLikesList(int btId, int page) {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_likeslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&count=10");
		url.append("&page=" + page);
		ServiceUtils.dout("getBottleLikesList url: " + url.toString());
		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("getBottleLikesList results:" + results);
			Gson gson = new Gson();
			BottleLikeListInfo btLikeInfo = gson.fromJson(results,
					BottleLikeListInfo.class);
			if (btLikeInfo.getResults().getAuthok() == 1) {
				mLikeEntries = btLikeInfo.getBtlikes_list();
				// if (null != mLikeEntries && mLikeEntries.size() > 0) {
				// Message message = Message.obtain(handler);
				// message.what = EXEU_BOTTLE_LIKELIST;
				// handler.sendMessage(message);
				// }
			} else {
				// Message message = handler.obtainMessage(EXEU_GET_DATA_ERROR,
				// btLikeInfo.getResults().getErrmsg());
				// handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
			// Message message = Message.obtain(handler);
			// message.what = EXEU_GET_BOTTLE_INFO_FAILED;
			// handler.sendMessage(message);
		}
	}

	private void refreshBottleLikesList(int btId) {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_likeslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&count=14");
		url.append("&page=1");
		ServiceUtils.dout("refreshBottleLikesList url: " + url.toString());
		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("refreshBottleLikesList results:" + results);
			Gson gson = new Gson();
			BottleLikeListInfo btLikeInfo = gson.fromJson(results,
					BottleLikeListInfo.class);
			if (btLikeInfo.getResults().getAuthok() == 1) {
				mLikeEntries = btLikeInfo.getBtlikes_list();
				Message message = Message.obtain(handler);
				message.what = EXEU_REFRESH_BOTTLE_LIST;
				handler.sendMessage(message);
			} else {
				Message message = handler.obtainMessage(EXEU_GET_DATA_ERROR,
						btLikeInfo.getResults().getErrmsg());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
			// Message message = Message.obtain(handler);
			// message.what = EXEU_GET_BOTTLE_INFO_FAILED;
			// handler.sendMessage(message);
		}
	}

	private void getBottleFeedList(int btId, int page) {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_feedslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&count=14");
		url.append("&page=" + page);
		ServiceUtils.dout("getBottleFeedList url: " + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());

			if (result == null) {
				return;
			}
			ServiceUtils.dout("getBottleFeedList results:" + result.toString());
			Gson gson = new Gson();
			BottleFeedListInfo bottleFeedListInfo = gson.fromJson(result,
					BottleFeedListInfo.class);
			if (bottleFeedListInfo.getResults().getAuthok() == 1) {
				mListEntries = bottleFeedListInfo.getBtfeeds_list();
				if (null != mListEntries && mListEntries.size() > 0) {
					Message message = Message.obtain(handler);
					message.what = EXEU_BOTTLE_FEEDLIST;
					handler.sendMessage(message);
				} else {
				}
			} else {
				Message message = handler.obtainMessage(EXEU_GET_DATA_ERROR,
						bottleFeedListInfo.getResults().getErrmsg());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
			Message message = Message.obtain(handler);
			message.what = EXEU_GET_BOTTLE_INFO_FAILED;
			handler.sendMessage(message);
		}
	}

	private void getMoreBottleFeedList(int btId, int page) {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_feedslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&count=10");
		url.append("&page=" + page);
		ServiceUtils.dout("getMoreBottleFeedList url: " + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());

			if (result == null) {
				return;
			}
			ServiceUtils.dout("getMoreBottleFeedList results:"
					+ result.toString());
			Gson gson = new Gson();
			BottleFeedListInfo bottleFeedListInfo = gson.fromJson(result,
					BottleFeedListInfo.class);
			if (bottleFeedListInfo.getResults().getAuthok() == 1) {
				mListEntries = bottleFeedListInfo.getBtfeeds_list();
				if (null != mListEntries && mListEntries.size() > 0) {
					Message message = Message.obtain(handler);
					message.what = EXEU_GET_MORE_CONTENT;
					handler.sendMessage(message);
				} else {
					Message message = handler
							.obtainMessage(EXEU_GET_DATA_NOTHING);
					handler.sendMessage(message);
				}
			} else {
				Message message = handler.obtainMessage(EXEU_GET_DATA_ERROR,
						bottleFeedListInfo.getResults().getErrmsg());
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			e.printStackTrace();
			Message message = Message.obtain(handler);
			message.what = EXEU_GET_BOTTLE_INFO_FAILED;
			handler.sendMessage(message);
		}
	}

	private void getFeedLocationList(int page) {
		StringBuffer url = new StringBuffer(UrlConfig.get_bt_feedslocation);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		url.append("&count=10");
		url.append("&page=" + page);
		ServiceUtils.dout("getFeedLocationList url: " + url.toString());

		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("getFeedLocationList results:"
					+ results.toString());
			Gson gson = new Gson();
			BottleFeedLocationInfo bottleFeedLocationInfo = gson.fromJson(
					results, BottleFeedLocationInfo.class);
			if (bottleFeedLocationInfo.getResults().getAuthok() == 1) {
				mLocationEntries = bottleFeedLocationInfo
						.getBtfeedslocation_list();
				Message message = handler.obtainMessage(EXEU_GET_LOCATION_LIST,
						bottleInfoEntry);
				handler.sendMessage(message);
			} else {

			}

		} catch (Exception e) {
			e.printStackTrace();
			Message message = Message.obtain(handler);
			message.what = EXEU_GET_BOTTLE_INFO_FAILED;
			handler.sendMessage(message);
		}
	}

	private void getBottleInfo(int btId) {
		StringBuffer url = new StringBuffer(UrlConfig.get_btinfo);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btId);
		ServiceUtils.dout("getBottleInfo url: " + url.toString());
		try {
			String results = HttpUtils.doGet(url.toString());

			if (results == null) {
				return;
			}
			ServiceUtils.dout("getBottleInfo results:" + results.toString());
			Gson gson = new Gson();
			BottleInfo bottleInfo = gson.fromJson(results, BottleInfo.class);

			if (bottleInfo.getResults().getAuthok() == 1) {
				PushNoticeInfoTable table = new PushNoticeInfoTable();
				pushInfo = table.getPushNoticeInfo(AppContext.getInstance()
						.getLogin_uid());
				if (null != pushInfo) {
					newBottleFeedCount = pushInfo.getNew_btfeed_count();
					newExchangeFeedCount = pushInfo.getNew_exfeed_count();
					newMessageCount = pushInfo.getNew_message_count();
					newNoticeCount = pushInfo.getNew_notice_count();
					message_content = pushInfo.getMessage_content();
					message_avatar = pushInfo.getMessage_avatar();
					newMaybeKownCount = pushInfo.getNew_maybeknow_count();
				}
				bottleInfoEntry = bottleInfo.getBtinfo();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	

	private void setViewValue(final BottleInfoEntry bottleInfoEntry) {
		rl_bt_detail_content.setVisibility(View.VISIBLE);
		try {
			
			
			Bitmap bitMap = HttpUtils.getBitmapFromUrl(this,
					bottleInfoEntry.getBt_avatar());
			Drawable drawable = new BitmapDrawable(bitMap);
			iv_avater.setBackgroundDrawable(drawable);
			iv_avater.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent spaceIntent = new Intent(BottleDetailActivity.this, UserSpaceActivity.class);
					spaceIntent.putExtra("ouid", bottleInfoEntry.getBt_uid());
					startActivity(spaceIntent);
				}
			});
			try {
				BottleTypeTable btt = new BottleTypeTable();
				entry = btt.getBottleType(bottleInfoEntry.getBttypeid());
				btConfigLoader.DisplayImage(entry.getBttype_sjwicon(), iv_bottle_type, R.drawable.bottle_type_1);
			} catch (Exception e) {
				e.printStackTrace();
				iv_bottle_type.setImageResource(R.drawable.bottle_type_1);
			}
			iv_bottle_type.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					btTypeId = bottleInfoEntry.getBttypeid();
					UICore.eventTask(BottleDetailActivity.this,
							BottleDetailActivity.this,
							EXEU_GET_BOTTLE_PRIV_OPERATION, "", null);
				}
			});
			String nickName = null;
			if (bottleInfoEntry.getBt_uid() != AppContext.getInstance().getLogin_uid()) {
				nickName = (!TextUtils.isEmpty(bottleInfoEntry.getBt_nickname())) ? ("<font color='#DA4A37'>"
								+ bottleInfoEntry.getBt_nickname() + "</font>") : "";
			} else {
				nickName = (!TextUtils.isEmpty(bottleInfoEntry.getBt_nickname())) ? ("<font color='#3F99D8'>"
						+ bottleInfoEntry.getBt_nickname() + "</font>") : "";
			}
					
			tv_nickname.setText(Html.fromHtml(nickName + bottleInfoEntry.getBt_feed()));
			if (!TextUtils.isEmpty(bottleInfoEntry.getBt_tag())) {
				tv_tag.setVisibility(View.VISIBLE);
				String locationTips = "<font color='#DA4A37'>"
						+ TextUtil.R("bottle_txt_location_tips") + "</font>";
				tv_tag.setText(Html.fromHtml(locationTips
						+ bottleInfoEntry.getBt_tag()));
				tv_tag.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(BottleDetailActivity.this,
								MapViewActivity.class);
						intent.putExtra("longitude",
								bottleInfoEntry.getBt_lng());
						intent.putExtra("latidute", bottleInfoEntry.getBt_lat());
						intent.putExtra("location",
								bottleInfoEntry.getBt_location());
						startActivity(intent);
					}
				});
			} else {
				tv_tag.setVisibility(View.GONE);
			}
			if (!TextUtils.isEmpty(bottleInfoEntry.getBt_copy_info())) {
				tv_copy.setVisibility(View.VISIBLE);
				String commentTips = "<font color='#DA4A37'>"
						+ TextUtil.R("bottle_txt_forward_tips") + "</font>";
				tv_copy.setText(Html.fromHtml(commentTips
						+ TextUtil.htmlEncode(bottleInfoEntry.getBt_copy_info())));
			} else {
				tv_copy.setVisibility(View.GONE);
			}
			if (!TextUtils.isEmpty(bottleInfoEntry.getBt_content())) {
				tv_message.setVisibility(View.VISIBLE);
				String messageTips = "<font color='#DA4A37'>"
						+ TextUtil.R("bottle_txt_copy_tips") + "</font>";
				tv_message
						.setText(Html.fromHtml(messageTips
								+ TextUtil.htmlEncode(bottleInfoEntry
										.getBt_content())));
			} else {
				tv_message.setVisibility(View.GONE);
			}
			if (!TextUtils.isEmpty(bottleInfoEntry.getBt_doing())) {
				tv_mood.setVisibility(View.VISIBLE);
				String moodTips = "<font color='#DA4A37'>"
						+ TextUtil.R("bottle_txt_mood_tips") + "</font>";
				tv_mood.setText(Html.fromHtml(moodTips
						+ TextUtil.htmlEncode(bottleInfoEntry.getBt_doing())));
			} else {
				tv_mood.setVisibility(View.GONE);
			}
			if (!TextUtils.isEmpty(bottleInfoEntry.getBt_location())) {
				String time = (!TextUtils.isEmpty(bottleInfoEntry.getBt_time())) ? ( "#" + bottleInfoEntry.getBt_time()) : "";
				ll_bottle_location.setVisibility(View.VISIBLE);
				tv_location.setText(time + bottleInfoEntry.getBt_location());
//				tv_location.setOnClickListener(new View.OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						Intent bottleDetailIntent = new Intent(
//								BottleDetailActivity.this,
//								BottleDetailActivity.class);
//						bottleDetailIntent.putExtra("btid", btId);
//						bottleDetailIntent.putExtra("type", 2);// 1，LikeList2,location
//						startActivity(bottleDetailIntent);
//					}
//				});
				
				tv_distance.setText(TextUtil.R("bottle_txt_comment_distance")+" "+bottleInfoEntry.getBt_opdistance()); 
			} else {
				ll_bottle_location.setVisibility(View.GONE);
			}
			
			/**************************瓶子传递动态***********************/
			if (!TextUtils.isEmpty(bottleInfoEntry.getBt_opfeed())) {
				ll_botle_op_location.setVisibility(View.VISIBLE);
				findViewById(R.id.line_feed).setVisibility(View.VISIBLE);
				RemoteImageView mOpAvatar = (RemoteImageView) mContentView.findViewById(R.id.bt_opavatar);
				try {
					mOpAvatar.setDefaultImage(R.drawable.avatar_default_small);
					mOpAvatar.setImageUrl(bottleInfoEntry.getBt_opavatar());
					mOpAvatar.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									Intent spaceIntent = new Intent(BottleDetailActivity.this, UserSpaceActivity.class);
									spaceIntent.putExtra("ouid", bottleInfoEntry.getBt_opuid());
									startActivity(spaceIntent);
								}
							});
				} catch (Exception e) {
					e.printStackTrace();
					mOpAvatar.setImageResource(R.drawable.avatar_default_small);
				}
				
				String onickName = (!TextUtils.isEmpty(bottleInfoEntry.getBt_opnickname())) ? ("<font color='#3F99D8'>"
						+ bottleInfoEntry.getBt_opnickname() + "</font>")
						: "";
				String otime = (!TextUtils.isEmpty(bottleInfoEntry.getBt_optime())) ? ("#" + bottleInfoEntry.getBt_optime()) : "";
				TextView mopfeedContent = (TextView)mContentView.findViewById(R.id.tv_feed_content);		
				mopfeedContent.setText(Html.fromHtml(onickName + TextUtil.htmlEncode(bottleInfoEntry.getBt_opfeed())));
				TextView mOp_location = (TextView)mContentView.findViewById(R.id.tv_oplocation); 
				if (!TextUtils.isEmpty(bottleInfoEntry.getBt_oplocation())) {
					mOp_location.setVisibility(View.VISIBLE);
					mOp_location.setText(otime + bottleInfoEntry.getBt_oplocation());
				} else {
					mOp_location.setVisibility(View.GONE);
				}

			} else {
				ll_botle_op_location.setVisibility(View.GONE);
			}

			/**************************从哪个瓶子复制而来***********************/
			if (!TextUtils.isEmpty(bottleInfoEntry.getBt_srcfeed())) {
				ll_botle_scrfeed.setVisibility(View.VISIBLE);	
				findViewById(R.id.line_feed).setVisibility(View.VISIBLE);
				RemoteImageView bt_srcavatar = (RemoteImageView) mContentView.findViewById(R.id.bt_scravatar);
				bt_srcavatar.setDefaultImage(R.drawable.avatar_default_small);
				bt_srcavatar.setImageUrl(bottleInfoEntry.getBt_srcavatar());
				
				String srcnickName = (!TextUtils.isEmpty(bottleInfoEntry.getBt_srcnickname())) ? ("<font color='#3F99D8'>"
						+ bottleInfoEntry.getBt_srcnickname() + "</font>") : "";
				TextView tv_srcfeed = (TextView)mContentView.findViewById(R.id.tv_srcfeed);
				tv_srcfeed.setText(Html.fromHtml(srcnickName + bottleInfoEntry.getBt_srcfeed()));
				
				String srctime = (!TextUtils.isEmpty(bottleInfoEntry.getBt_srctime())) ? ("#" + bottleInfoEntry.getBt_srctime()) : "";
			    TextView tv_srclocation = (TextView)mContentView.findViewById(R.id.tv_srclocation);
				tv_srclocation.setText(srctime + bottleInfoEntry.getBt_srclocation());
				ll_botle_scrfeed.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						showSrcFeedDialog(bottleInfoEntry);	
					}
				});
			} else {
				ll_botle_scrfeed.setVisibility(View.GONE);
			}
			
			if (bottleInfoEntry.getBt_pic_locked() == 1) {
				rl_bottle_content_photo.setVisibility(View.GONE);
				ll_bottle_photo_locked.setVisibility(View.VISIBLE);
			} else {
				ll_bottle_photo_locked.setVisibility(View.GONE);
				if (!TextUtils.isEmpty(bottleInfoEntry.getBt_smallpic())) {
					rl_bottle_content_photo.setVisibility(View.VISIBLE);
					findViewById(R.id.ll_layout_drawing).setVisibility(View.VISIBLE);
					
					ServiceUtils.dout(TAG + " rl_bottle_content_photo:"+bottleInfoEntry.getBt_smallpic());
					
					imageLoader.DisplayImage(bottleInfoEntry.getBt_smallpic(),
							iv_photo, R.drawable.album_nophoto);
					
					iv_photo.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							byte[] tempBytes = null;
							try {
								String filename = ServiceUtils.convertUrlToFileName(bottleInfoEntry.getBt_smallpic());
								tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
										android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename)));
							} catch (Exception e) {
								e.printStackTrace();
							}
							Intent bigPicIntent = new Intent(BottleDetailActivity.this, PhotoDetailActivity.class);
							bigPicIntent.putExtra("pic_big", bottleInfoEntry.getBt_bigpic());
							bigPicIntent.putExtra("thumbnail", tempBytes);
							BottleDetailActivity.this.startActivity(bigPicIntent);
						}
					});
					
					
					if (bottleInfoEntry.getBt_allow_tuya() == 1) {
						findViewById(R.id.ll_layout_drawing).setVisibility(View.VISIBLE);
						bt_drawing.setVisibility(View.VISIBLE);
						bt_drawing.setOnClickListener(new View.OnClickListener() {
							
							@Override
							public void onClick(View v) {
								File file = imageLoader.fileCache.getFile(bottleInfoEntry.getBt_smallpic());
								byte[] tempBytes = null;
								try {
									tempBytes = ServiceUtils.readStream(new FileInputStream(file));
								} catch (Exception e) {
									e.printStackTrace();
								}
								Intent bigPicIntent = new Intent(BottleDetailActivity.this, PhotoDetailActivity.class);
								bigPicIntent.putExtra("pic_big", bottleInfoEntry.getBt_bigpic());
								bigPicIntent.putExtra("thumbnail", tempBytes);
								bigPicIntent.putExtra("paintType", AppContext.PAINT_BT);
								bigPicIntent.putExtra("return_type", BottleDetailActivity.class.getSimpleName());
								bigPicIntent.putExtra("btid", btId);
								bigPicIntent.putExtra("isToDraw", true);
								startActivity(bigPicIntent);	
								
							}
						});
					}else {
						bt_drawing.setVisibility(View.GONE);
					}
					
					if (bottleInfoEntry.getBt_enable_tuya()== 0) {
						bt_allow_draw.setVisibility(View.GONE);
					}else {
						findViewById(R.id.ll_layout_drawing).setVisibility(View.VISIBLE);
						bt_allow_draw.setVisibility(View.VISIBLE);
						if (bottleInfoEntry.getBt_enable_tuya()== 1) {
							bt_allow_draw.setText(TextUtil.R("bottle_txt_allow_draw"));
							bt_allow_draw.setBackgroundResource(R.drawable.btn_red_try);
							bt_allow_draw.setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									UICore.eventTask(BottleDetailActivity.this, BottleDetailActivity.this, EXEU_SET_BTPIC_PAINT_SUCCESS, "", 1);
								}
							});
						}else {
							bt_allow_draw.setText(TextUtil.R("bottle_txt_not_allow_draw"));
							bt_allow_draw.setBackgroundResource(R.drawable.btn_gray_try);
							bt_allow_draw.setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									UICore.eventTask(BottleDetailActivity.this, BottleDetailActivity.this, EXEU_SET_BTPIC_PAINT_SUCCESS, "", 0);
								}
							});
						}
					}
					
				} else {
					rl_bottle_content_photo.setVisibility(View.GONE);
					findViewById(R.id.ll_layout_drawing).setVisibility(View.GONE);
				}
			}

			if (type == 1) {
				if (bottleInfoEntry.getBt_showaddress() == 0) {
					iv_menu.setVisibility(View.INVISIBLE);
				}else {
					iv_menu.setVisibility(View.VISIBLE);
				}
				rl_like.setVisibility(View.VISIBLE);
				iv_map.setVisibility(View.GONE);

				switch (bottleInfoEntry.getBt_liked()) {
				case 0:
					iv_like_icon.setBackgroundDrawable(this.getResources()
							.getDrawable(R.drawable.like_gray2));
					break;
				case 1:
					iv_like_icon.setBackgroundDrawable(this.getResources()
							.getDrawable(R.drawable.like_red2));
					break;
				case 2:
					iv_like_icon.setBackgroundDrawable(this.getResources()
							.getDrawable(R.drawable.like_black2));
					break;
				default:
					break;
				}

				if (bottleInfoEntry.getBt_like_enable() == 1) {
					like_num.setTextColor(BottleDetailActivity.this.getResources().getColor(R.color.gray));
					rl_button_like.setBackgroundDrawable(BottleDetailActivity.this.getResources().getDrawable(R.drawable.photo_pill));
					rl_button_like.setOnClickListener(this);
				} else {
					like_num.setTextColor(BottleDetailActivity.this.getResources().getColor(R.color.white));
					rl_button_like.setBackgroundDrawable(BottleDetailActivity.this.getResources().getDrawable(R.drawable.photo_pill_dark));
				}
			} else if (type == 2) {
				iv_menu.setVisibility(View.VISIBLE);
				rl_like.setVisibility(View.GONE);
				iv_map.setVisibility(View.VISIBLE);
				bottle_lat = bottleInfoEntry.getBt_lat();
				bottle_lon = bottleInfoEntry.getBt_lng();
				location = bottleInfoEntry.getBt_location();
				UICore.eventTask(this, BottleDetailActivity.this,
						EXEU_BOTTLE_LOAD_MAP, null, null);
			}

			if (bottleInfoEntry.getBt_allow_spread() == 1) {
				bt_forward.setVisibility(View.VISIBLE);
				bt_forward.setOnClickListener(this);
			} else {
				bt_forward.setVisibility(View.GONE);
			}
			if (bottleInfoEntry.getBt_copy_enable() == 1) {
				bt_copy.setVisibility(View.VISIBLE);
				bt_copy.setOnClickListener(this);
			} else {
				bt_copy.setVisibility(View.GONE);
			}
			if (null != mLikeEntries && mLikeEntries.size() > 0) {
				like_num.setText(mLikeEntries.size() + "");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
	private void showSrcFeedDialog(final BottleInfoEntry bottleInfoEntry) {
		String[] choices = new String[]{TextUtil.R("bottle_txt_feed_single"),TextUtil.R("bottle_txt_feed_location")};
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {
							Intent intent = new Intent(BottleDetailActivity.this, BottleSingleActivity.class);
							intent.putExtra("btid", bottleInfoEntry.getBt_srcbtid());
							startActivity(intent);
						} else {
							dialog.dismiss();
							Intent intent = new Intent(BottleDetailActivity.this,MapViewActivity.class);
							intent.putExtra("longitude",bottleInfoEntry.getBt_srclng());
							intent.putExtra("latidute",bottleInfoEntry.getBt_srclat());
							intent.putExtra("location",bottleInfoEntry.getBt_srclocation());
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}
	
	/**
	 * 设置瓶子照片涂鸦权限接口
	 * @param btid 瓶子ID
	 * @param optype 设置是否允许涂鸦。选择项：不允许（0）、允许（1）
	 */
	public void setBtpicPaint(int btid,int optype) {
		this.btId = btid;
		StringBuffer url = new StringBuffer(UrlConfig.set_btpic_paint);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&btid=" + btid);
		url.append("&optype=" + optype);
		ServiceUtils.dout("setBtpicPaint url:" + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("setBtpicPaint result:" + result);
			if (result != null) {
				JSONObject object = new JSONObject(result);
				JSONObject resultObj = object.getJSONObject("results");
				int authok = resultObj.getInt("success");
				if (authok == 0) {
					String errmsg = resultObj.getString("errmsg");
					Message msg = Message.obtain(handler, EXEU_GET_DATA_ERROR, errmsg);
					handler.sendMessage(msg);
				} else {
					String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, EXEU_SET_BTPIC_PAINT_SUCCESS, successmsg);
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void setFeedLikeLayout(List<BottleFeedListEntry> mListEntries) {
		if (null != mFeedCommentContent) {
			mFeedCommentContent.removeAllViews();
		}
		View convertView = null;
		if (null != mListEntries && mListEntries.size() > 0) {
			for (int i = 0; i < mListEntries.size(); i++) {
				final BottleFeedListEntry message = mListEntries.get(i);
				convertView = LayoutInflater.from(this).inflate(
						R.layout.bottle_comment_list_detail_item, null);
				RemoteImageView mAuthorView = (RemoteImageView) convertView
						.findViewById(R.id.comment_profile_photo);
				mAuthorView.setDefaultImage(R.drawable.avatar_default_small);
				mAuthorView.setImageUrl(message.getFeed_avatar());
				mAuthorView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent spaceIntent = new Intent(BottleDetailActivity.this, UserSpaceActivity.class);
						spaceIntent.putExtra("ouid", message.getFeed_uid());
						startActivity(spaceIntent);
					}
				});
				ImageView mLink = (ImageView) convertView
						.findViewById(R.id.iv_feed_comment_white);
				TextView mfeedContent = (TextView) convertView
						.findViewById(R.id.tv_comment_feed_content);
				TextView mfeedReplyComment = (TextView) convertView
						.findViewById(R.id.tv_comment_feed_reply);
				ImageView mfeedReplyPhoto = (ImageView) convertView
						.findViewById(R.id.photo);
				Button feed_reply_comment = (Button) convertView
						.findViewById(R.id.feed_reply_comment);
				TextView mfeedTime = (TextView) convertView
						.findViewById(R.id.tv_comment_feed_time);
				RelativeLayout comment_content_photo = (RelativeLayout) convertView
						.findViewById(R.id.rl_bottle_content_photo);

				ServiceUtils.dout(TAG + " message.getFeed_avatar():"
						+ message.getFeed_avatar());

				String nickName = null;
				if (message.getFeed_uid() != AppContext.getInstance()
						.getLogin_uid()) {
					nickName = (!TextUtils.isEmpty(message.getFeed_nickname())) ? ("<font color='#DA4A37'>"
							+ message.getFeed_nickname() + "</font>")
							: "";
				} else {
					nickName = (!TextUtils.isEmpty(message.getFeed_nickname())) ? ("<font color='#3F99D8'>"
							+ message.getFeed_nickname() + "</font>")
							: "";
				}

				String time = (message.getFeed_time() != null && message
						.getFeed_time().length() > 0) ? ("<font color='#666666'>"
						+ " #" + message.getFeed_time() + "</font>")
						: "";
				final String location = (message.getFeed_location() != null && message
						.getFeed_location().trim().length() > 0) ? ("<font color='#666666'>"
						+ " @" + message.getFeed_location() + "</font>")
						: "";
				String feed_content = message.getFeed_isnew() == 1 ? ("<font color='#DA4A37'>"
						+ TextUtil.htmlEncode(message.getFeed_content()) + "</font>")
						: TextUtil.htmlEncode(message.getFeed_content());
				mfeedContent.setText(Html.fromHtml(nickName + " "
						+ feed_content));
				mfeedTime.setText(Html.fromHtml(time + location));
				mfeedTime.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(location.length()>0){
							if(message.getLocation_delete_enable() == 1){
								final Context dialogContext = new ContextThemeWrapper(
										BottleDetailActivity.this,
										android.R.style.Theme_Light);
								String[] choices = new String[2];
								choices[0] = getString(R.string.bottle_txt_check_location);
								choices[1] = getString(R.string.bottle_txt_clean_location);

								final ListAdapter adapter = new ArrayAdapter<String>(
										dialogContext,
										android.R.layout.simple_list_item_1,
										choices);

								final AlertDialog.Builder builder = new AlertDialog.Builder(
										dialogContext);
								builder.setTitle(R.string.system_info);
								builder.setSingleChoiceItems(
										adapter,
										-1,
										new DialogInterface.OnClickListener() {

											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
												if (which == 0) {
													Intent intent = new Intent(
															BottleDetailActivity.this,
															MapViewActivity.class);
													intent.putExtra(
															"longitude",
															message.getFeed_lng());
													intent.putExtra(
															"latidute",
															message.getFeed_lat());
													intent.putExtra(
															"location",
															message.getFeed_location());
													startActivity(intent);
													
												} else {
													UICore.eventTask(BottleDetailActivity.this, BottleDetailActivity.this, EXEU_DELETE_LOCATION, "", message);
												}

											}
										});
								builder.create().show();
						} else {
							final Context dialogContext = new ContextThemeWrapper(
									BottleDetailActivity.this,
									android.R.style.Theme_Light);
							String[] choices = new String[1];
							choices[0] = getString(R.string.bottle_txt_check_location);

							final ListAdapter adapter = new ArrayAdapter<String>(
									dialogContext,
									android.R.layout.simple_list_item_1,
									choices);

							final AlertDialog.Builder builder = new AlertDialog.Builder(
									dialogContext);
							builder.setTitle(R.string.system_info);
							builder.setSingleChoiceItems(
									adapter,
									-1,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.dismiss();
											if (which == 0) {
												Intent intent = new Intent(
														BottleDetailActivity.this,
														MapViewActivity.class);
												intent.putExtra(
														"longitude",
														message.getFeed_lng());
												intent.putExtra(
														"latidute",
														message.getFeed_lat());
												intent.putExtra(
														"location",
														message.getFeed_location());
												startActivity(intent);
											}
										}
									});
							builder.create().show();
						}
						}
						
					}
				});
				
				if (message.getFeed_type() == 1) {
					comment_content_photo.setVisibility(View.VISIBLE);
					mfeedReplyComment.setVisibility(View.VISIBLE);
					mfeedReplyPhoto.setVisibility(View.VISIBLE);
					if (message.getFeed_uid() != AppContext.getInstance()
						.getLogin_uid()) {
						feed_reply_comment.setVisibility(View.VISIBLE);
					}else {
						feed_reply_comment.setVisibility(View.GONE);
					}
					
					mLink.setVisibility(View.GONE);

					mfeedContent.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							if (message.getFeed_uid() != AppContext
									.getInstance().getLogin_uid()) {

								if ((!TextUtils.isEmpty(location))
										&& (!TextUtils.isEmpty(message
												.getFeed_content()))) {
									final Context dialogContext = new ContextThemeWrapper(
											BottleDetailActivity.this,
											android.R.style.Theme_Light);
									String[] choices = new String[2];
									choices[0] = getString(R.string.bottle_txt_reply_comment);
									choices[1] = getString(R.string.bottle_txt_check_location);

									final ListAdapter adapter = new ArrayAdapter<String>(
											dialogContext,
											android.R.layout.simple_list_item_1,
											choices);

									final AlertDialog.Builder builder = new AlertDialog.Builder(
											dialogContext);
									builder.setTitle(R.string.system_info);
									builder.setSingleChoiceItems(
											adapter,
											-1,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
													if (which == 0) {
														Intent commentIntent = new Intent(
																BottleDetailActivity.this,
																ExpandEditActivity.class);
														Bundle commentBundle = new Bundle();
														commentBundle
																.putString(
																		"from_type",
																		AppContext.REPLY_COMMENT);
														commentBundle
																.putString(
																		"return_type",
																		"bottledetailactivity");
														commentBundle
																.putInt("commentid",
																		message.getCommentid());
														commentIntent
																.putExtras(commentBundle);
														startActivityForResult(
																commentIntent,
																0);
													} else {
														Intent intent = new Intent(
																BottleDetailActivity.this,
																MapViewActivity.class);
														intent.putExtra(
																"longitude",
																message.getFeed_lng());
														intent.putExtra(
																"latidute",
																message.getFeed_lat());
														intent.putExtra(
																"location",
																message.getFeed_location());
														startActivity(intent);
													}

												}
											});
									builder.create().show();
								} else if (!TextUtils.isEmpty(location)) {

									final Context dialogContext = new ContextThemeWrapper(
											BottleDetailActivity.this,
											android.R.style.Theme_Light);
									String[] choices = new String[1];
									choices[0] = getString(R.string.bottle_txt_check_location);

									final ListAdapter adapter = new ArrayAdapter<String>(
											dialogContext,
											android.R.layout.simple_list_item_1,
											choices);

									final AlertDialog.Builder builder = new AlertDialog.Builder(
											dialogContext);
									builder.setTitle(R.string.system_info);
									builder.setSingleChoiceItems(
											adapter,
											-1,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
													Intent intent = new Intent(
															BottleDetailActivity.this,
															MapViewActivity.class);
													intent.putExtra(
															"longitude",
															message.getFeed_lng());
													intent.putExtra(
															"latidute",
															message.getFeed_lat());
													intent.putExtra("location",
															message.getFeed_location());
													startActivity(intent);
												}
											});
									builder.create().show();
								} else if (!TextUtils.isEmpty(message
										.getFeed_content())) {

									final Context dialogContext = new ContextThemeWrapper(
											BottleDetailActivity.this,
											android.R.style.Theme_Light);
									String[] choices = new String[1];
									choices[0] = getString(R.string.bottle_txt_reply_comment);

									final ListAdapter adapter = new ArrayAdapter<String>(
											dialogContext,
											android.R.layout.simple_list_item_1,
											choices);

									final AlertDialog.Builder builder = new AlertDialog.Builder(
											dialogContext);
									builder.setTitle(R.string.system_info);
									builder.setSingleChoiceItems(
											adapter,
											-1,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();

													Intent commentIntent = new Intent(
															BottleDetailActivity.this,
															ExpandEditActivity.class);
													Bundle commentBundle = new Bundle();
													commentBundle
															.putString(
																	"from_type",
																	AppContext.REPLY_COMMENT);
													commentBundle
															.putInt("commentid",
																	message.getCommentid());
													commentIntent
															.putExtras(commentBundle);
													startActivityForResult(
															commentIntent, 0);
												}
											});
									builder.create().show();
								}
							} else {
								if (!TextUtils.isEmpty(location)) {

									final Context dialogContext = new ContextThemeWrapper(
											BottleDetailActivity.this,
											android.R.style.Theme_Light);
									String[] choices = new String[1];
									choices[0] = getString(R.string.bottle_txt_check_location);

									final ListAdapter adapter = new ArrayAdapter<String>(
											dialogContext,
											android.R.layout.simple_list_item_1,
											choices);

									final AlertDialog.Builder builder = new AlertDialog.Builder(
											dialogContext);
									builder.setTitle(R.string.system_info);
									builder.setSingleChoiceItems(
											adapter,
											-1,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
													Intent intent = new Intent(
															BottleDetailActivity.this,
															MapViewActivity.class);
													intent.putExtra(
															"longitude",
															message.getFeed_lng());
													intent.putExtra(
															"latidute",
															message.getFeed_lat());
													intent.putExtra("location",
															message.getFeed_location());
													startActivity(intent);
												}
											});
									builder.create().show();
								}
							}
						}
					});

					if (!TextUtils.isEmpty(message.getFeed_replycomment())) {
						mfeedReplyComment.setVisibility(View.VISIBLE);
						mfeedReplyComment.setText(message
								.getFeed_replycomment());
					} else {
						mfeedReplyComment.setVisibility(View.GONE);
					}
					if (!TextUtils.isEmpty(message.getFeed_commentpic())) {
						comment_content_photo.setVisibility(View.VISIBLE);
						mfeedReplyPhoto.setVisibility(View.VISIBLE);
						imageLoader.DisplayImage(message.getFeed_commentpic(),
								mfeedReplyPhoto, R.drawable.album_nophoto);
						mfeedReplyPhoto
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										if (!TextUtils.isEmpty(message
												.getFeed_commentpic_tuya())) {
											showCommentPicFeedDialog(message);
										} else {
											byte[] tempBytes = null;
											try {
												String filename = ServiceUtils
														.convertUrlToFileName(message
																.getFeed_commentpic());
												tempBytes = ServiceUtils
														.readStream(new FileInputStream(
																new File(
																		android.os.Environment
																				.getExternalStorageDirectory()
																				+ "/"
																				+ AppContext.BottleTimelineIcon
																				+ "/"
																				+ filename)));
											} catch (Exception e) {
												e.printStackTrace();
											}
											Intent bigPicIntent = new Intent(
													BottleDetailActivity.this,
													PhotoDetailActivity.class);
											bigPicIntent
													.putExtra(
															"pic_big",
															message.getFeed_commentpic_big());
											bigPicIntent.putExtra("thumbnail",
													tempBytes);
											BottleDetailActivity.this
													.startActivity(bigPicIntent);

										}
									}
								});
					} else {
						comment_content_photo.setVisibility(View.GONE);
						mfeedReplyPhoto.setVisibility(View.GONE);
					}

					feed_reply_comment.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							Intent commentIntent = new Intent(BottleDetailActivity.this,ExpandEditActivity.class);
							Bundle commentBundle = new Bundle();
							commentBundle.putString("from_type",AppContext.REPLY_COMMENT);
							commentBundle.putString("return_type","bottledetailactivity");
							commentBundle.putInt("commentid",message.getCommentid());
							commentIntent.putExtras(commentBundle);
							startActivityForResult(commentIntent,0);
						}
					});
					
				} else {
					comment_content_photo.setVisibility(View.GONE);
					mfeedReplyComment.setVisibility(View.GONE);
					mfeedReplyPhoto.setVisibility(View.GONE);
					feed_reply_comment.setVisibility(View.GONE);
					mLink.setVisibility(View.VISIBLE);
					if (!TextUtils.isEmpty(location)) {
						mfeedContent
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										Intent bottleDetailIntent = new Intent(
												BottleDetailActivity.this,
												BottleDetailActivity.class);
										bottleDetailIntent.putExtra("btid",
												btId);
										bottleDetailIntent.putExtra("type", 2);// 1，LikeList2,location
										startActivity(bottleDetailIntent);
									}
								});
					}
				}
				mFeedCommentContent.addView(convertView);
				mFeedCommentContent.invalidate();
			}
		}
	}

	private void showCommentPicFeedDialog(final BottleFeedListEntry message) {
		String[] choices = new String[]{TextUtil.R("bottle_txt_feed_comment_pic"),TextUtil.R("bottle_txt_feed_comment_tuya")};
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {

							byte[] tempBytes = null;
							try {
								String filename = ServiceUtils.convertUrlToFileName(message.getFeed_commentpic());
								tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
										android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename)));
							} catch (Exception e) {
								e.printStackTrace();
							}
							Intent bigPicIntent = new Intent(BottleDetailActivity.this, PhotoDetailActivity.class);
							bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_big());
							bigPicIntent.putExtra("thumbnail", tempBytes);
							BottleDetailActivity.this.startActivity(bigPicIntent);
							
						} else {
							Intent bigPicIntent = new Intent(BottleDetailActivity.this, PhotoDetailActivity.class);
							bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_tuya());
							BottleDetailActivity.this.startActivity(bigPicIntent);
						}
					}
				});
		builder.create().show();
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);

		if (null != intent) {
			if (intent.getBooleanExtra("need_refresh", false)) {
				page = 1;
				UICore.eventTask(this, BottleDetailActivity.this,
						EXEU_GET_BOTTLE_INFO, "", null);
			}
		}
		

		if ( resultCode == RESULT_OK ) {
			switch ( requestCode ) {

				case ACTION_REQUEST_FEATHER:

					// send a notification to the media scanner
					updateMedia( mOutputFilePath );

					// update the preview with the result
					loadAsync( intent.getData() );
//					onSaveCompleted( mOutputFilePath );
					
					/************正常保存*************/
					if ( null != mSessionId ) {
						deleteSession( mSessionId );
					}
					mSessionId = null;
					/*************************/
					
					mOutputFilePath = null;
					break;
			}
		} else if ( resultCode == RESULT_CANCELED ) {
			switch ( requestCode ) {
				case ACTION_REQUEST_FEATHER:

					// feather was cancelled without saving.
					// we need to delete the entire session
					if ( null != mSessionId ) deleteSession( mSessionId );

					// delete the result file, if exists
					if ( mOutputFilePath != null ) {
						deleteFileNoThrow( mOutputFilePath );
						mOutputFilePath = null;
					}
					break;
			}
		}
	}
	/**
	 * Load the incoming Image
	 * 
	 * @param uri
	 */
	private void loadAsync( final Uri uri ) {
		Log.i( TAG, "loadAsync: " + uri );

		Drawable toRecycle = iv_photo.getDrawable();
		if ( toRecycle != null && toRecycle instanceof BitmapDrawable ) {
			if ( ( (BitmapDrawable) iv_photo.getDrawable() ).getBitmap() != null )
				( (BitmapDrawable) iv_photo.getDrawable() ).getBitmap().recycle();
		}
		iv_photo.setImageDrawable( null );
		fileUri = null;

		DownloadAsync task = new DownloadAsync();
		task.execute( uri );
	}
	
	class DownloadAsync extends AsyncTask<Uri, Void, Bitmap> implements OnCancelListener {

		ProgressDialog mProgress;
		private Uri mUri;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			mProgress = new ProgressDialog( BottleDetailActivity.this );
			mProgress.setIndeterminate( true );
			mProgress.setCancelable( true );
			mProgress.setMessage( "Loading image..." );
			mProgress.setOnCancelListener( this );
			mProgress.show();
		}

		@Override
		protected Bitmap doInBackground( Uri... params ) {
			mUri = params[0];
			Bitmap bitmap = null;

//			while ( mImageContainer.getWidth() < 1 ) {
//				try {
//					Thread.sleep( 1 );
//				} catch ( InterruptedException e ) {
//					e.printStackTrace();
//				}
//			}
//
//			final int w = mImageContainer.getWidth();
//			Log.d( TAG, "width: " + w );
			ImageSizes sizes = new ImageSizes();
			bitmap = DecodeUtils.decode( BottleDetailActivity.this, mUri, imageWidth, imageHeight, sizes );
			return bitmap;
		}

		@Override
		protected void onPostExecute( Bitmap result ) {
			super.onPostExecute( result );

			if ( mProgress.getWindow() != null ) {
				mProgress.dismiss();
			}

			if ( result != null ) {
				setImageURI( mUri, result );
			} else {
				Toast.makeText( BottleDetailActivity.this, "Failed to load image " + mUri, Toast.LENGTH_SHORT ).show();
			}
		}

		@Override
		public void onCancel( DialogInterface dialog ) {
			Log.i( TAG, "onProgressCancel" );
			this.cancel( true );
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			Log.i( TAG, "onCancelled" );
		}

	}

	/**
	 * lo-res process completed, ask the user if wants to process also the hi-res image
	 * 
	 * @param filepath
	 *           lo-res file name ( in case we want to delete it )
	 */
	private void onSaveCompleted( final String filepath ) {

		if ( mSessionId != null ) {

			DialogInterface.OnClickListener yesListener = new DialogInterface.OnClickListener() {

				@Override
				public void onClick( DialogInterface dialog, int which ) {
					if ( null != mSessionId ) {
						processHD( mSessionId );
					}
					mSessionId = null;
				}
			};

			DialogInterface.OnClickListener noListener = new DialogInterface.OnClickListener() {

				@Override
				public void onClick( DialogInterface dialog, int which ) {

					if ( null != mSessionId ) {
						deleteSession( mSessionId );
					}

					if ( !isFinishing() ) {
						dialog.dismiss();
					}
					mSessionId = null;
				}
			};

			Dialog dialog = new AlertDialog.Builder( this ).setTitle( "HiRes" )
					.setMessage( "A low-resolution image was created. Do you want to save the hi-res image too?" )
					.setPositiveButton( android.R.string.yes, yesListener ).setNegativeButton( android.R.string.no, noListener )
					.setCancelable( false ).create();

			dialog.show();
		}
	}
	
	/**
	 * Start the hi-res image processing.
	 * 
	 */
	private void processHD( final String session_name ) {

		Log.i( TAG, "processHD: " + session_name );

		// get a new file for the hi-res file
		File destination = Utility.getNextFileName();

		try {
			if ( destination == null || !destination.createNewFile() ) {
				Log.e( TAG, "Failed to create a new file" );
				return;
			}
		} catch ( IOException e ) {
			Log.e( TAG, e.getMessage() );
			Toast.makeText( this, e.getLocalizedMessage(), Toast.LENGTH_SHORT ).show();
			return;
		}

		String error = null;

		// Now we need to fetch the session information from the content provider
		FeatherContentProvider.SessionsDbColumns.Session session = null;

		Uri sessionUri = FeatherContentProvider.SessionsDbColumns.getContentUri( session_name );

		// this query will return a cursor with the informations about the given session
		Cursor cursor = getContentResolver().query( sessionUri, null, null, null, null );

		if ( null != cursor ) {
			session = FeatherContentProvider.SessionsDbColumns.Session.Create( cursor );
			cursor.close();
		}

		if ( null != session ) {
			// Print out the session informations
			Log.d( TAG, "session.id: " + session.id ); // session _id
			Log.d(TAG, "session.name: " + session.session ); // session name
			Log.d( TAG, "session.ctime: " + session.ctime ); // creation time
			Log.d( TAG, "session.file_name: " + session.file_name ); // original file, it is the same you passed in the
																								// startActivityForResult Intent

			// Now, based on the session information we need to retrieve
			// the list of actions to apply to the hi-res image
			Uri actionsUri = FeatherContentProvider.ActionsDbColumns.getContentUri( session.session );

			// this query will return the list of actions performed on the original file, during the FeatherActivity session.
			// Now you can apply each action to the hi-res image to replicate the same result on the bigger image
			cursor = getContentResolver().query( actionsUri, null, null, null, null );

			if ( null != cursor ) {
				// If the cursor is valid we will start a new asynctask process to query the cursor
				// and apply all the actions in a queue
				HDAsyncTask task = new HDAsyncTask( Uri.parse( session.file_name ), destination.getAbsolutePath(), session_name );
				task.execute( cursor );
			} else {
				error = "Failed to retrieve the list of actions!";
			}
		} else {
			error = "Failed to retrieve the session informations";
		}

		if ( null != error ) {
			Toast.makeText( this, error, Toast.LENGTH_LONG ).show();
		}
	}
	/**
	 * AsyncTask for Hi-Res image processing
	 * 
	 * @author alessandro
	 * 
	 */
	private class HDAsyncTask extends AsyncTask<Cursor, Integer, MoaHD.Error> {

		Uri uri_;
		String dstPath_;
		ProgressDialog progress_;
		String session_;
		ExifInterfaceWrapper exif_;

		/**
		 * Initialize the HiRes async task
		 * 
		 * @param source
		 *           - source image file
		 * @param destination
		 *           - destination image file
		 * @param session_id
		 *           - the session id used to retrieve the list of actions
		 */
		public HDAsyncTask( Uri source, String destination, String session_id ) {
			uri_ = source;
			dstPath_ = destination;
			session_ = session_id;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progress_ = new ProgressDialog( BottleDetailActivity.this );
			progress_.setIndeterminate( true );
			progress_.setTitle( "Processing Hi-res image" );
			progress_.setMessage( "Loading image..." );
			progress_.setProgressStyle( ProgressDialog.STYLE_SPINNER );
			progress_.setCancelable( false );
			progress_.show();
		}

		@Override
		protected void onProgressUpdate( Integer... values ) {
			super.onProgressUpdate( values );

			final int index = values[0];
			final int total = values[1];
			String message = "";

			if ( index == -1 )
				message = "Saving image...";
			else
				message = "Applying action " + ( index + 1 ) + " of " + ( total );

			progress_.setMessage( message );

			Log.d( TAG, index + "/" + total + ", message: " + message );
		}

		@Override
		protected Error doInBackground( Cursor... params ) {
			Cursor cursor = params[0];

			MoaHD.Error result = Error.UnknownError;

			if ( null != cursor ) {

				// Initialize the class to perform HD operations
				MoaHD moa = new MoaHD();

				// try to load the source image
				result = loadImage( moa );
				Log.d( TAG, "moa.load: " + result.name() );

				// if image is loaded
				if ( result == Error.NoError ) {

					final int total_actions = cursor.getCount();
					
					Log.d( TAG, "total actions: " + total_actions );

					if ( cursor.moveToFirst() ) {

						// get the total number of actions in the queue
						// we're adding also the 'load' and the 'save' action to the total count

						// now for each action in the given cursor, apply the action to
						// the MoaHD instance
						do {
							// send a progress notification to the progressbar dialog
							publishProgress( cursor.getPosition(), total_actions );

							// load the action from the current cursor
							Action action = Action.Create( cursor );
							if ( null != action ) {
								Log.d( TAG, "executing: " + action.id + "(" + action.session_id + " on " + action.ctime + ") = "
										+ action.getActions() );
								
								// apply a list of actions to the current image
								moa.applyActions( action.getActions() );
							} else {
								Log.e( TAG, "Woa, something went wrong! Invalid action returned" );
							}

							// move the cursor to next position
						} while ( cursor.moveToNext() );
					}

					// at the end of all the operations we need to save
					// the modified image to a new file
					publishProgress( -1, -1 );
					result = moa.save( dstPath_ );
					Log.d( TAG, "moa.save: " + result.name() );

					if ( result != Error.NoError ) {
						Log.e( TAG, "failed to save the image to " + dstPath_ );
					}

					// ok, now we can save the source image EXIF tags
					// to the new image
					if ( null != exif_ ) {
						saveExif( exif_, dstPath_ );
					}

				} else {
					Log.e( TAG, "Failed to load file" );
				}
				cursor.close();

				// and unload the current bitmap. Note that you *MUST* call this method to free the memory allocated with the load
				// method
				result = moa.unload();
				Log.d( TAG, "moa.unload: " + result.name() );

				// finally dispose the moahd instance
				moa.dispose();
			}

			return result;
		}

		/**
		 * Save the Exif tags to the new image
		 * 
		 * @param originalExif
		 * @param filename
		 */
		private void saveExif( ExifInterfaceWrapper originalExif, String filename ) {
			// ok, now we can save back the EXIF tags
			// to the new file
			ExifInterfaceWrapper newExif = null;
			try {
				newExif = new ExifInterfaceWrapper( dstPath_ );
			} catch ( IOException e ) {
				e.printStackTrace();
			}
			if ( null != newExif && null != originalExif ) {
				originalExif.copyTo( newExif );
				// this should be changed because the editor already rotate the image
				newExif.setAttribute( ExifInterfaceWrapper.TAG_ORIENTATION, "0" );
				// let's update the software tag too
				newExif.setAttribute( ExifInterfaceWrapper.TAG_SOFTWARE, "Aviary " + FeatherActivity.SDK_VERSION );
				// ...and the modification date
				newExif.setAttribute( ExifInterfaceWrapper.TAG_DATETIME, ExifInterfaceWrapper.formatDate( new Date() ) );
				try {
					newExif.saveAttributes();
				} catch ( IOException e ) {
					e.printStackTrace();
				}
			}
		}

		@Override
		protected void onPostExecute( MoaHD.Error result ) {
			super.onPostExecute( result );

			if ( progress_.getWindow() != null ) {
				progress_.dismiss();
			}

			// in case we had an error...
			if ( result != Error.NoError ) {
				Toast.makeText( BottleDetailActivity.this, "There was an error: " + result.name(), Toast.LENGTH_SHORT ).show();
				return;
			}

			// finally notify the MediaScanner of the new generated file
			updateMedia( dstPath_ );

			// now ask the user if he want to see the saved image
			new AlertDialog.Builder( BottleDetailActivity.this ).setTitle( "File saved" )
					.setMessage( "File saved in " + dstPath_ + ". Do you want to see the HD file?" )
					.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {

						@Override
						public void onClick( DialogInterface dialog, int which ) {

							Intent intent = new Intent( Intent.ACTION_VIEW );

							String filepath = dstPath_;
							if ( !filepath.startsWith( "file:" ) ) {
								filepath = "file://" + filepath;
							}
							intent.setDataAndType( Uri.parse( filepath ), "image/jpeg" );
							startActivity( intent );

						}
					} ).setNegativeButton( android.R.string.no, null ).show();

			// we don't need the session anymore, now we can delete it.
			Log.d( TAG, "delete session: " + session_ );
			deleteSession( session_ );
		}

		private Error loadImage( MoaHD moa ) {
			MoaHD.Error result = Error.UnknownError;
			final String srcPath = IOUtils.getRealFilePath( BottleDetailActivity.this, uri_ );
			if ( srcPath != null ) {

				// Let's try to load the EXIF tags from
				// the source image
				try {
					exif_ = new ExifInterfaceWrapper( srcPath );
				} catch ( IOException e ) {
					e.printStackTrace();
				}
				result = moa.load( srcPath );
			} else {

				if ( SystemUtils.isHoneyComb() ) {
					InputStream stream = null;
					try {
						stream = getContentResolver().openInputStream( uri_ );
					} catch ( Exception e ) {
						result = Error.FileNotFoundError;
						e.printStackTrace();
					}
					if ( stream != null ) {
						try {
							result = moa.load( stream );
						} catch ( Exception e ) {
							result = Error.DecodeError;
						}
					} else {
						Log.e( TAG, "stream is null!" );
					}
				} else {
					ParcelFileDescriptor fd = null;
					try {
						fd = getContentResolver().openFileDescriptor( uri_, "r" );
					} catch ( FileNotFoundException e ) {
						e.printStackTrace();
						result = Error.FileNotFoundError;
					}

					if ( null != fd ) {
						result = moa.load( fd.getFileDescriptor() );
					}
				}
			}
			return result;
		}
	}
	/**
	 * Given an Uri load the bitmap into the current ImageView and resize it to fit the image container size
	 * 
	 * @param uri
	 */
	private boolean setImageURI( final Uri uri, final Bitmap bitmap ) {

		Log.d(TAG, "image size: " + bitmap.getWidth() + "x" + bitmap.getHeight() );
		iv_photo.setImageBitmap( bitmap );
		iv_photo.setBackgroundDrawable( null );

		fileUri = uri;
		return true;
	}
	/**
	 * We need to notify the MediaScanner when a new file is created. In this way all the gallery applications will be notified too.
	 * 
	 * @param file
	 */
	private void updateMedia( String filepath ) {
		Log.i(TAG, "updateMedia: " + filepath );
		MediaScannerConnection.scanFile( getApplicationContext(), new String[] { filepath }, null, null );
	}
	/**
	 * Delete a file without throwing any exception
	 * 
	 * @param path
	 * @return
	 */
	private boolean deleteFileNoThrow( String path ) {
		File file;
		try {
			file = new File( path );
		} catch ( NullPointerException e ) {
			return false;
		}

		if ( file.exists() ) {
			return file.delete();
		}
		return false;
	}
	/**
	 * Delete the session and all it's actions. We do not need it anymore.<br />
	 * Note that this is optional. All old sessions are automatically removed in Feather.
	 * 
	 * @param session_id
	 */
	private void deleteSession( final String session_id ) {
		Uri uri = FeatherContentProvider.SessionsDbColumns.getContentUri( session_id );
		getContentResolver().delete( uri, null, null );
	}
	
	private void setFeedLocationLayout(
			List<BottleFeedLocationEntry> mLocationEntries) {
		if (null != mFeedCommentContent) {
			mFeedCommentContent.removeAllViews();
		}
		View convertView = null;
		if (null != mLocationEntries && mLocationEntries.size() > 0) {
			for (int i = 0; i < mLocationEntries.size(); i++) {
				final BottleFeedLocationEntry message = mLocationEntries.get(i);
				convertView = LayoutInflater.from(this).inflate(
						R.layout.bottle_comment_list_detail_item, null);
				RelativeLayout feed_item_comment = (RelativeLayout) convertView
						.findViewById(R.id.feed_item_comment);
				RemoteImageView mAuthorView = (RemoteImageView) convertView
						.findViewById(R.id.comment_profile_photo);
				ImageView mLink = (ImageView) convertView
						.findViewById(R.id.iv_feed_comment_white);
				mLink.setImageResource(R.drawable.feed_gray);
				mLink.setVisibility(View.VISIBLE);
				TextView mfeedContent = (TextView) convertView
						.findViewById(R.id.tv_comment_feed_content);
				TextView mfeedReplyComment = (TextView) convertView
						.findViewById(R.id.tv_comment_feed_reply);
				TextView mfeedTime = (TextView) convertView
						.findViewById(R.id.tv_comment_feed_time);
				mfeedReplyComment.setVisibility(View.GONE);
				
				Button feed_reply_comment = (Button) convertView
						.findViewById(R.id.feed_reply_comment);
				feed_reply_comment.setVisibility(View.GONE);
				RelativeLayout comment_content_photo = (RelativeLayout) convertView
						.findViewById(R.id.rl_bottle_content_photo);
				comment_content_photo.setVisibility(View.GONE);

				mAuthorView.setDefaultImage(R.drawable.avatar_default_small);
				mAuthorView.setImageUrl(message.getFeed_avatar());
				mAuthorView.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent spaceIntent = new Intent(BottleDetailActivity.this, UserSpaceActivity.class);
						spaceIntent.putExtra("ouid", message.getFeed_uid());
						startActivity(spaceIntent);
					}
				});

				String nickName = null;
				
				if (message.getFeed_uid() != AppContext.getInstance()
						.getLogin_uid()) {
					nickName = (message.getFeed_nickname() != null && message
							.getFeed_nickname().length() > 0) ? ("<font color='#DA4A37'>"
							+ message.getFeed_nickname() + "</font>")
							: "";
				} else {
					nickName = (message.getFeed_nickname() != null && message
							.getFeed_nickname().length() > 0) ? ("<font color='#3F99D8'>"
							+ message.getFeed_nickname() + "</font>")
							: "";
				}
				
			   String time = (message.getFeed_time() != null && message
						.getFeed_time().length() > 0) ? ("<font color='#666666'>"
						+ " #" + message.getFeed_time() + "</font>")
						: "";
				final String location = (message.getFeed_location() != null && message
						.getFeed_location().trim().length() > 0) ? ("<font color='#666666'>"
						+ " @" + message.getFeed_location() + "</font>")
						: "";
				String feed_content = message.getFeed_isnew() == 1 ? ("<font color='#DA4A37'>"
						+ TextUtil.htmlEncode(message.getFeed_content()) + "</font>")
						: TextUtil.htmlEncode(message.getFeed_content());

				mfeedContent.setText(Html.fromHtml(nickName + " "
						+ feed_content));
				mfeedTime.setText(Html.fromHtml(time + location));
				if (!TextUtils.isEmpty(location)) {
					mfeedTime.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(location.length()>0){
								if(message.getLocation_delete_enable() == 1){
									final Context dialogContext = new ContextThemeWrapper(
											BottleDetailActivity.this,
											android.R.style.Theme_Light);
									String[] choices = new String[2];
									choices[0] = getString(R.string.bottle_txt_check_location);
									choices[1] = getString(R.string.bottle_txt_clean_location);

									final ListAdapter adapter = new ArrayAdapter<String>(
											dialogContext,
											android.R.layout.simple_list_item_1,
											choices);

									final AlertDialog.Builder builder = new AlertDialog.Builder(
											dialogContext);
									builder.setTitle(R.string.system_info);
									builder.setSingleChoiceItems(
											adapter,
											-1,
											new DialogInterface.OnClickListener() {

												public void onClick(
														DialogInterface dialog,
														int which) {
													dialog.dismiss();
													if (which == 0) {
														Intent intent = new Intent(
																BottleDetailActivity.this,
																MapViewActivity.class);
														intent.putExtra(
																"longitude",
																message.getFeed_lng());
														intent.putExtra(
																"latidute",
																message.getFeed_lat());
														intent.putExtra(
																"location",
																message.getFeed_location());
														startActivity(intent);
														
													} else {
														UICore.eventTask(BottleDetailActivity.this, BottleDetailActivity.this, EXEU_DELETE_LOCATION, "", message.getLocation_objid());
													}

												}
											});
									builder.create().show();
							} else {
								final Context dialogContext = new ContextThemeWrapper(
										BottleDetailActivity.this,
										android.R.style.Theme_Light);
								String[] choices = new String[1];
								choices[0] = getString(R.string.bottle_txt_check_location);

								final ListAdapter adapter = new ArrayAdapter<String>(
										dialogContext,
										android.R.layout.simple_list_item_1,
										choices);

								final AlertDialog.Builder builder = new AlertDialog.Builder(
										dialogContext);
								builder.setTitle(R.string.system_info);
								builder.setSingleChoiceItems(
										adapter,
										-1,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
												if (which == 0) {
													Intent intent = new Intent(
															BottleDetailActivity.this,
															MapViewActivity.class);
													intent.putExtra(
															"longitude",
															message.getFeed_lng());
													intent.putExtra(
															"latidute",
															message.getFeed_lat());
													intent.putExtra(
															"location",
															message.getFeed_location());
													startActivity(intent);
												}
											}
										});
								builder.create().show();
							}
						 }
						}
					});	
				}
				mFeedCommentContent.addView(convertView);
				mFeedCommentContent.invalidate();
			}
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case EXEU_BOTTLE_FEEDLIST:
				receiver = new PushBroadcastReceiver();
				IntentFilter filter = new IntentFilter();
				filter.addAction("push");
				registerReceiver(receiver, filter);
				setViewValue(bottleInfoEntry);
				if (mLikeEntries != null && mLikeEntries.size() > 0) {
					gridAdapter = new GridLikeAdapter(this, mLikeEntries);
					like_grid.setAdapter(gridAdapter);
				}
				setFeedLikeLayout(mListEntries);
				rv.mfooterViewText.setVisibility(View.VISIBLE);
				rv.finishRefresh();
				break;
			case EXEU_BOTTLE_LIKELIST:
				gridAdapter = new GridLikeAdapter(this, mLikeEntries);
				like_grid.setAdapter(gridAdapter);
				break;
			case EXEU_GET_BOTTLE_INFO:
				setViewValue((BottleInfoEntry) msg.obj);
				break;
			case EXEU_GET_BOTTLE_INFO_FAILED:
				this.onToast(TextUtil.R("error_data"));
				break;
			case EXEU_GET_DATA_ERROR:
				this.onToast((String) msg.obj);
				break;
			case EXEU_SET_BTPIC_PAINT_SUCCESS:
				UICore.eventTask(this, BottleDetailActivity.this,
						EXEU_REFRESH_BOTTLE_LIST, "", null);
				break;
			case EXEU_REFRESH_CONTENT:
				ll_content.removeAllViews();
				setViewValue(bottleInfoEntry);
				gridAdapter = new GridLikeAdapter(this, mLikeEntries);
				like_grid.setAdapter(gridAdapter);
				setFeedLikeLayout(mListEntries);
				// elasticScrollView.onRefreshComplete();
				// elasticScrollView.invalidate();
				ll_content.addView(mContentView);
				rv.finishRefresh();
				break;
			case EXEU_BOTTLE_LOAD_MAP:
				iv_map.setImageBitmap(bitmap);
				iv_map.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(BottleDetailActivity.this,
								MapViewActivity.class);
						intent.putExtra("longitude", bottle_lon);
						intent.putExtra("latidute", bottle_lat);
						intent.putExtra("location", location);
						startActivity(intent);
					}
				});
				break;
			case EXEU_GET_LOCATION_LIST:
				setViewValue((BottleInfoEntry) msg.obj);
				setFeedLocationLayout(mLocationEntries);
				rv.finishRefresh();
				break;
			case EXEU_SEND_BOTTLE_PRIV_SUCCESS:
				final Bundle bundle = msg.getData();
				try {
					BottleTypeTable table = new BottleTypeTable();
					BottleTypeEntry bottleEntry = table.getBottleType(bundle.getInt("type"));
					int locationSelect = bottleEntry.getBttype_location_select();
					String[] choices = new String[2];
					if (locationSelect > 1) {
						choices[0] = getString(R.string.choose_location_here_throw);
						choices[1] = getString(R.string.choose_location_search_throw);
					} else {
						choices = new String[1];
						choices[0] = getString(R.string.choose_location_here_throw);
					}
					chooseAction(choices, locationSelect , bundle.getInt("type"));
				} catch (Exception e) {
					e.printStackTrace();
				}

				break;
			case EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE:
				onToast((String) msg.obj);
				break;
			case EXEU_SEND_BOTTLE_PRIV_FAILED:
				onToast((String) msg.obj);
				break;
			case EXEU_LIKE_OPERATION_FAILED:
				onToast((String) msg.obj);
				break;
			case EXEU_LIKE_OPERATION:
				UICore.eventTask(this, BottleDetailActivity.this,
						EXEU_REFRESH_BOTTLE_LIST, "", null);
				break;
			case EXEU_UNLIKE_OPERATION:
				UICore.eventTask(this, BottleDetailActivity.this,
						EXEU_REFRESH_BOTTLE_LIST, "", null);
				break;
			case EXEU_REFRESH_BOTTLE_LIST:
				ServiceUtils.dout(TAG + " EXEU_REFRESH_BOTTLE_LIST :"
						+ mLikeEntries.size());
				if (likeType == 1) {
					iv_like_icon.setBackgroundDrawable(this.getResources()
							.getDrawable(R.drawable.like_red2));
				} else if (likeType == 2) {
					iv_like_icon.setBackgroundDrawable(this.getResources()
							.getDrawable(R.drawable.like_black2));
				}
				rl_button_like.setOnClickListener(null);
				gridAdapter = new GridLikeAdapter(this, mLikeEntries);
				like_grid.setAdapter(gridAdapter);
				break;
			case EXEU_GET_DATA_NOTHING:
				rv.mfooterViewText.setVisibility(View.INVISIBLE);
				onToast(TextUtil.R("no_more_data"));
				rv.finishRefresh();
				break;
			case EXEU_GET_MORE_CONTENT:
				setMoreFeeds(mListEntries);
				rv.finishRefresh();
				break;
			case throw_bottle_init_location:
//				try {
//					int bottleid = Integer.parseInt(msg.obj.toString());
//					Intent intent2 = new Intent(this, ThrowBottleSettingActivity.class);
//					intent2.putExtra("bttype_id", bottleid);
//					intent2.putExtra("bt_geo_lng", longitude);
//					intent2.putExtra("bt_geo_lat", latitude);
//					startActivity(intent2);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
				break;
			case EXEU_DELETE_LOCATION_SUCCESS:
				if (!TextUtils.isEmpty((String) msg.obj)) {
					onToast((String) msg.obj);
				}
				switch (type) {
				case 1:
					UICore.eventTask(this, BottleDetailActivity.this,
							EXEU_REFRESH_FEED_LIST, "", null);
					break;
				case 2:
					UICore.eventTask(this, BottleDetailActivity.this,
							EXEU_REFRESH_LOCATION_LIST, "", null);
					break;
				default:
					break;
				}
				
				break;
			case EXEU_DELETE_LOCATION_FAILED:
				onToast((String) msg.obj);
				break;
			case EXEU_REFRESH_FEED_LIST:
				setFeedLikeLayout(mListEntries);
				break;
			case EXEU_REFRESH_LOCATION_LIST:
				setFeedLocationLayout(mLocationEntries);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
		return false;
	}

	private void setMoreFeeds(List<BottleFeedListEntry> mListEntries2) {
		for (int i = 0; i < mListEntries2.size(); i++) {
			final BottleFeedListEntry message = mListEntries2.get(i);
			View convertView = LayoutInflater.from(this).inflate(
					R.layout.bottle_comment_list_detail_item, null);
			RemoteImageView mAuthorView = (RemoteImageView) convertView
					.findViewById(R.id.comment_profile_photo);
			mAuthorView.setDefaultImage(R.drawable.avatar_default_small);
			mAuthorView.setImageUrl(message.getFeed_avatar());
			ImageView mLink = (ImageView) convertView
					.findViewById(R.id.iv_feed_comment_white);
			TextView mfeedContent = (TextView) convertView
					.findViewById(R.id.tv_comment_feed_content);
			TextView mfeedTime = (TextView) convertView
					.findViewById(R.id.tv_comment_feed_time);

			TextView mfeedReplyComment = (TextView) convertView
					.findViewById(R.id.tv_comment_feed_reply);
			ImageView mfeedReplyPhoto = (ImageView) convertView
					.findViewById(R.id.photo);
			Button feed_reply_comment = (Button) convertView
					.findViewById(R.id.feed_reply_comment);
			
			RelativeLayout comment_content_photo = (RelativeLayout) convertView
					.findViewById(R.id.rl_bottle_content_photo);

			ServiceUtils.dout(TAG + " message.getFeed_avatar():"
					+ message.getFeed_avatar());

			String nickName = null;
			if (message.getFeed_uid() != AppContext.getInstance()
					.getLogin_uid()) {
				nickName = (message.getFeed_nickname() != null && message
						.getFeed_nickname().length() > 0) ? ("<font color='#DA4A37'>"
						+ message.getFeed_nickname() + "</font>")
						: "";
			} else {
				nickName = (message.getFeed_nickname() != null && message
						.getFeed_nickname().length() > 0) ? ("<font color='#3F99D8'>"
						+ message.getFeed_nickname() + "</font>")
						: "";
			}

			String time = (message.getFeed_time() != null && message
					.getFeed_time().length() > 0) ? ("<font color='#666666'>"
					+ " #" + message.getFeed_time() + "</font>") : "";
			String location = (message.getFeed_location() != null && message
					.getFeed_location().trim().length() > 0) ? ("<font color='#666666'>"
					+ " @" + message.getFeed_location() + "</font>")
					: "";
			String feed_content = message.getFeed_isnew() == 1 ? ("<font color='#DA4A37'>"
					+ TextUtil.htmlEncode(message.getFeed_content()) + "</font>")
					: TextUtil.htmlEncode(message.getFeed_content());

			mfeedContent.setText(Html.fromHtml(nickName + feed_content));
			mfeedTime.setText(Html.fromHtml(time + location));
			mfeedTime.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(message.getLocation_delete_enable() == 1){
							final Context dialogContext = new ContextThemeWrapper(
									BottleDetailActivity.this,
									android.R.style.Theme_Light);
							String[] choices = new String[2];
							choices[0] = getString(R.string.bottle_txt_check_location);
							choices[1] = getString(R.string.bottle_txt_clean_location);

							final ListAdapter adapter = new ArrayAdapter<String>(
									dialogContext,
									android.R.layout.simple_list_item_1,
									choices);

							final AlertDialog.Builder builder = new AlertDialog.Builder(
									dialogContext);
							builder.setTitle(R.string.system_info);
							builder.setSingleChoiceItems(
									adapter,
									-1,
									new DialogInterface.OnClickListener() {

										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.dismiss();
											if (which == 0) {
												Intent intent = new Intent(
														BottleDetailActivity.this,
														MapViewActivity.class);
												intent.putExtra(
														"longitude",
														message.getFeed_lng());
												intent.putExtra(
														"latidute",
														message.getFeed_lat());
												intent.putExtra(
														"location",
														message.getFeed_location());
												startActivity(intent);
												
											} else {
												UICore.eventTask(BottleDetailActivity.this, BottleDetailActivity.this, EXEU_DELETE_LOCATION, "", message.getLocation_objid());
											}

										}
									});
							builder.create().show();
					} else {
						final Context dialogContext = new ContextThemeWrapper(
								BottleDetailActivity.this,
								android.R.style.Theme_Light);
						String[] choices = new String[1];
						choices[0] = getString(R.string.bottle_txt_check_location);

						final ListAdapter adapter = new ArrayAdapter<String>(
								dialogContext,
								android.R.layout.simple_list_item_1,
								choices);

						final AlertDialog.Builder builder = new AlertDialog.Builder(
								dialogContext);
						builder.setTitle(R.string.system_info);
						builder.setSingleChoiceItems(
								adapter,
								-1,
								new DialogInterface.OnClickListener() {
									public void onClick(
											DialogInterface dialog,
											int which) {
										dialog.dismiss();
										if (which == 0) {
											Intent intent = new Intent(
													BottleDetailActivity.this,
													MapViewActivity.class);
											intent.putExtra(
													"longitude",
													message.getFeed_lng());
											intent.putExtra(
													"latidute",
													message.getFeed_lat());
											intent.putExtra(
													"location",
													message.getFeed_location());
											startActivity(intent);
										}
									}
								});
						builder.create().show();
					}
					
				}
			});
			if (message.getFeed_type() == 1) {
				comment_content_photo.setVisibility(View.VISIBLE);
				mfeedReplyComment.setVisibility(View.VISIBLE);
				mfeedReplyPhoto.setVisibility(View.VISIBLE);
				feed_reply_comment.setVisibility(View.VISIBLE);
				mLink.setVisibility(View.GONE);
				if (null != message.getFeed_replycomment()
						&& message.getFeed_replycomment().length() > 0) {
					mfeedReplyComment.setVisibility(View.VISIBLE);
					mfeedReplyComment.setText(message.getFeed_replycomment());
				} else {
					mfeedReplyComment.setVisibility(View.GONE);
				}
				if (!TextUtils.isEmpty(message.getFeed_commentpic())) {
					comment_content_photo.setVisibility(View.VISIBLE);
					mfeedReplyPhoto.setVisibility(View.VISIBLE);
					imageLoader.DisplayImage(message.getFeed_commentpic(),
							mfeedReplyPhoto, R.drawable.avatar_default_small);
					mfeedReplyPhoto
							.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									byte[] tempBytes = null;
									try {
										String filename = ServiceUtils.convertUrlToFileName(message.getFeed_commentpic());
										tempBytes = ServiceUtils.readStream(new FileInputStream(new File(
												android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename)));
									} catch (Exception e) {
										e.printStackTrace();
									}
									Intent bigPicIntent = new Intent(BottleDetailActivity.this, PhotoDetailActivity.class);
									bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_big());
									bigPicIntent.putExtra("thumbnail", tempBytes);
									BottleDetailActivity.this.startActivity(bigPicIntent);
								}
							});
				} else {
					comment_content_photo.setVisibility(View.GONE);
					mfeedReplyPhoto.setVisibility(View.GONE);
				}

				feed_reply_comment.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent commentIntent = new Intent(BottleDetailActivity.this,ExpandEditActivity.class);
						Bundle commentBundle = new Bundle();
						commentBundle.putString("from_type",AppContext.REPLY_COMMENT);
						commentBundle.putString("return_type","bottledetailactivity");
						commentBundle.putInt("commentid",message.getCommentid());
						commentIntent.putExtras(commentBundle);
						startActivityForResult(commentIntent,0);
					}
				});

			} else {
				comment_content_photo.setVisibility(View.GONE);
				mfeedReplyComment.setVisibility(View.GONE);
				mfeedReplyPhoto.setVisibility(View.GONE);
				feed_reply_comment.setVisibility(View.GONE);
				mLink.setVisibility(View.VISIBLE);
			}
			mFeedCommentContent.addView(convertView);
			mFeedCommentContent.invalidate();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (null != bitmap) {
			bitmap.recycle();
			bitmap = null;
		}
		try {
			if (receiver != null) {
				unregisterReceiver(receiver);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class GridLikeAdapter extends BaseAdapter {
		private Context context;
		private List<BottleLikeEntry> arrayList;


		public GridLikeAdapter(Context context, List<BottleLikeEntry> arrayList) {
			this.context = context;
			this.arrayList = arrayList;
		}

		@Override
		public int getCount() {
			return (null != arrayList && arrayList.size() > 0) ? arrayList.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			return (null != arrayList && arrayList.size() > 0) ? arrayList.get(position) : null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.bottle_like_avatar_listitem, null);
				holder.mheadView = (RemoteImageView) convertView.findViewById(R.id.head_photo);
				holder.mLikeView = (ImageView) convertView.findViewById(R.id.like_photo);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			BottleLikeEntry item = (BottleLikeEntry) getItem(position);
//			holder.mheadView.setDefaultImage(R.drawable.avatar_default_small);
//			holder.mheadView.setImageUrl(item.getLike_avatar(),
//					AppContext.BottleTimelineIcon, position, like_grid);
			holder.mheadView.setDefaultImage(R.drawable.avatar_default_small);
			holder.mheadView.setImageUrl(item.getLike_avatar());

			switch (item.getLike_type()) {
			case 1:// 喜欢
				holder.mLikeView.setImageResource(R.drawable.like_red2);
				break;
			case 2:// 不喜欢
				holder.mLikeView.setImageResource(R.drawable.like_black2);
				break;
			default:
				holder.mLikeView.setVisibility(View.GONE);
				break;
			}
			return convertView;
		}

		class ViewHolder {
			RemoteImageView mheadView;
			ImageView mLikeView;
		}
	}

	private void initSateMenu() {
		SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu);
		menu.setVisibility(View.VISIBLE);
		if (CanvasWidth >= 480) {
			menu.setSatelliteDistance(200);
		} else {
			menu.setSatelliteDistance(100);
		}
		List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>();
		items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile));
		items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto));
		items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt));
		items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt));
		items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto));
		menu.addItems(items);
		menu.setOnItemClickedListener(new SateliteClickedListener() {

			public void eventOccured(int id) {
				switch (id) {
				case menu_sendbt: // 扔瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent throwIntent = new Intent(
										BottleDetailActivity.this,
										ChooseBottleActivity.class);
								throwIntent.putExtra("type", "throw");
								startActivity(throwIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_gainbt: // 捞瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent tryIntent = new Intent(
										BottleDetailActivity.this,
										ChooseBottleActivity.class);
								tryIntent.putExtra("type", "try");
								startActivity(tryIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exphoto: // 交换照片
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent exchangeInfoIntent = new Intent(
										BottleDetailActivity.this,
										ChooseFriendActivity.class);
								exchangeInfoIntent
										.putExtra(
												"choose_friend_type",
												AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE);
								startActivity(exchangeInfoIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exprofile: // 交换资料
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								LoginUserInfoTable userTable = new LoginUserInfoTable();
								LoginUserInfoEntry userEntry = userTable
										.getLoginUserInfo(AppContext
												.getInstance().getLogin_uid());
								if (userEntry.getBasicinfo_fullfill() == 0) {
									handler.sendEmptyMessage(user_baseinfo_notfull);
								} else {
									Intent exchangeFileIntent = new Intent(
											BottleDetailActivity.this,
											ChooseFriendActivity.class);
									exchangeFileIntent
											.putExtra(
													"choose_friend_type",
													AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE);
									startActivity(exchangeFileIntent);
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_uploadphoto:
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent intent = new Intent(BottleDetailActivity.this, ExpandEditActivity.class);
								Bundle extras = new Bundle();
								extras.putString("from_type", AppContext.UPLOAD_PHOTO);
								extras.putInt("albumid", 0);
								extras.putInt("ouid", AppContext.getInstance().getLogin_uid());
								intent.putExtras(extras);
								startActivity(intent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				default:
					break;
				}
			}
		});
	}

	public void doMessageAction() {

		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String[] choices = new String[2];
		if (newNoticeCount > 0) {
			choices[0] = newNoticeCount
					+ getString(R.string.bottle_txt_notice_list);
		} else {
			choices[0] = getString(R.string.bottle_txt_notice_list);
		}
		if (newMessageCount > 0) {
			choices[1] = newMessageCount
					+ getString(R.string.bottle_txt_message_list);
		} else {
			choices[1] = getString(R.string.bottle_txt_message_list);
		}

		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {
							Intent intent = new Intent(
									BottleDetailActivity.this,
									NoticeListActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(
									BottleDetailActivity.this,
									MessageListActivity.class);
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}

	public void doFeedsAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		final List<String> choices = new ArrayList<String>(); 
		if (newBottleFeedCount > 0) {
			choices.add(newBottleFeedCount + getString(R.string.bottle_txt_new_bottle_feed));
		}
		if (newExchangeFeedCount > 0) {
			choices.add(newExchangeFeedCount + getString(R.string.bottle_txt_new_exchange_feed));
		}
		if (newNoticeCount > 0) {
			choices.add(newNoticeCount + getString(R.string.bottle_txt_notice_list));
		}
		if (newMessageCount > 0) {
			choices.add(newMessageCount + getString(R.string.bottle_txt_message_list));
		}
		if (newMaybeKownCount > 0) {
			choices.add(newMaybeKownCount + getString(R.string.bottle_txt_new_maybe_kown));
		}
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices);
		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_bottle_feed)) != -1) {
							Intent intent = new Intent(BottleDetailActivity.this, HomeActivity.class);
							AppContext.getInstance().setCurrentItem(1);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_exchange_feed)) != -1) {
							Intent intent = new Intent(BottleDetailActivity.this, HomeActivity.class);
							AppContext.getInstance().setCurrentItem(0);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_notice_list)) != -1) {
							Intent intent = new Intent(BottleDetailActivity.this, NoticeListActivity.class);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_message_list)) != -1) {
							Intent intent = new Intent(BottleDetailActivity.this, MessageListActivity.class);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_maybe_kown)) != -1) {
							Intent intent = new Intent(BottleDetailActivity.this, HomeActivity.class);
							AppContext.getInstance().setCurrentItem(2);
							AppContext.getInstance().setGotoMaybeKown(true);
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}

	public void pushNoticeUpdateUI() {
//		if (newMessageCount + newNoticeCount > 0) {
//			messageView.setImageResource(R.drawable.bottom_menu_notice_red);
//		} else {
//			messageView.setImageResource(R.drawable.bottom_menu_notice_yellow);
//		}
		if (newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount  + newMaybeKownCount > 0) {
			bottomLayout.setVisibility(View.VISIBLE);
			contentView.setText(message_content);
			btnCount.setText(newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount + "");
			avatarView.setDefaultImage(R.drawable.avatar_default_big);
			avatarView.setImageUrl(message_avatar);
		} else {
			bottomLayout.setVisibility(View.GONE);
		}
	}

	public class PushBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				newBottleFeedCount = bundle.getInt("bottle_feed_count");
				newExchangeFeedCount = bundle.getInt("exchange_feed_count");
				newMessageCount = bundle.getInt("message_count");
				newNoticeCount = bundle.getInt("notice_count");
				message_content = bundle.getString("message_content");
				message_avatar = bundle.getString("message_avatar");
				newMaybeKownCount = bundle.getInt("maybe_kown_count");
				pushNoticeUpdateUI();
			}
		}
	}
	
	private void chooseAction(String[] choices, final int locationSelected, final int bottleId) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {
							Intent intent2 = new Intent(BottleDetailActivity.this, ThrowBottleSettingActivity.class);
							intent2.putExtra("bttype_id", bottleId);
							intent2.putExtra("bt_geo_lng", AppContext.getInstance().getLongitude());
							intent2.putExtra("bt_geo_lat", AppContext.getInstance().getLatitude());
							startActivity(intent2);
						} else {
							Intent intent = new Intent(BottleDetailActivity.this, ChooseLocationTabsActivity.class);
							intent.putExtra("type", "throw");
							intent.putExtra("bottleId", bottleId);
							intent.putExtra("locationSelect", locationSelected);
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}
	
	
	/**
	 * 
	 * @param objtype 要清除的位置的类型：选择项：（1）瓶子动态的位置信息、（2）交换动态留言的位置信息、（3）照片评论的位置信息、（4）私信的位置信息、（5）照片的位置信息
	 * @param objid objid
	 */
	private void deleteLocation(String objtype,String objid) {
		StringBuffer url = new StringBuffer(UrlConfig.delete_location);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&objtype=" + objtype);
		url.append("&objid=" + objid);
		ServiceUtils.dout("deleteLocation url:" + url.toString());
		try {
			String result = HttpUtils.doGet(url.toString());
			ServiceUtils.dout("deleteLocation result:" + result);
			JSONObject obj = new JSONObject(result);
			JSONObject resultObj = obj.getJSONObject("results");
			int success = resultObj.getInt("success");
			String errmsg = resultObj.getString("errmsg");
			String successmsg = resultObj.getString("successmsg");
			if (success == 1) {
				Message message = handler.obtainMessage(
						EXEU_DELETE_LOCATION_SUCCESS, successmsg);
				handler.sendMessage(message);
			} else {
				Message message = handler.obtainMessage(
						EXEU_DELETE_LOCATION_FAILED, errmsg);
				handler.sendMessage(message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
